Passing external functions to scripts

Jint scripts can use functions defined in the hosting environment by defining named delegates. This can be very useful when complex functions could be difficult to create in JavaScript, of if the scripts may have to call business methods which are already implemented 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 print which is actually a substitue to Console.WriteLine(object)

JintEngine engine = new JintEngine()
  .SetFunction("print", new Action<object>(Console.WriteLine));

engine.Run(@"
  var i = 1;
  print(i);
";

// 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.

Last edited Nov 25, 2009 at 6:56 AM by sebastienros, version 4

Comments

zhihongwang Jul 27, 2011 at 8:48 PM 
You have to call jintEngine.AddPermission(new System.Security.Permissions.UIPermission(System.Security.Permissions.UIPermissionWindow.SafeTopLevelWindows));
Or else simply call jintEngine.DisableSecurity();

jstrider39 Jan 11, 2011 at 4:53 AM 
When I run the MessageBox example below I get security exception; Does any one know why? Is it because Jint does not know how to handle the DialogResult return type?

engine.SetFunction("alert", new Jint.Delegates.Func<string, DialogResult>(MessageBox.Show));
engine.Run(@"
function square(x) {
alert('Hi Mike');
return x * x;
}");
engine.Run("square(5);");