Passing external functions to scripts
in the host application.
When Jint encounters a function to execute, it first looks into the locally defined ones, and if none is found, then searches in the parameterized ones. As they are delegates, a dynamic invocation is then run, and optionaly returns a value.
To declare an external function, the SetFunction()
method must be called. It takes the name to use in the script to call it, and a Delegate pointing to the implementation.
SetFunction(string name, Delegate function)
Using C# 3.0 delegates
The delegate can be an anonymous implementation, or a reference to an already existing method. For instance, the following example declares a function named
which is actually a substitue to Console.WriteLine(object)
JintEngine engine = new JintEngine()
.SetFunction("print", new Action<object>(Console.WriteLine));
var i = 1;
// Displays 1 on the Console
Using Jint delegates for .NET 2.0
In addition to standard delegates in C# 3.0, Jint comes with a set of predefined ones to allow the same simplicity of declaration:
public delegate void Action();
public delegate void Action<T1, T2>(T1 t1, T2 t2);
public delegate void Action<T1, T2, T3>(T1 t1, T2 t2, T3 t3);
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T t);
public delegate TResult Func<T1, T2, TResult>(T1 t1, T2 t2);
public delegate TResult Func<T1, T2, T3, TResult>(T1 t1, T2 t2, T3 t3);
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 t1, T2 t2, T3 t3, T4 t4);
Those delegates are declared in the namespace Jint.Delegates