Search code examples
c#v8clearscript

C# ClearScript V8ScriptEngine - How to add a static function to the engine


I want to ask if somebody of you know, how i can add a static function to the V8ScriptEngine instance? I'm switching from Jint and don't know how this works with V8.

In Jint i passed a function name and a delegate and it works. _engine.SetValue(sfa.Name, Delegate.CreateDelegate(getType(types.ToArray()), method));

In V8 is no equivalent for this.

In V8 are only functions to add a specific type or an object.


Solution

  • Suppose you have a class with a static method:

    public static class Functions {
        public static void PrintNumber(int n) => Console.WriteLine("The number is {0}.", n);
    }
    

    You can expose the method like this:

    _engine.AddHostObject("printNumber", new Action<int>(Functions.PrintNumber));
    

    And now JavaScript code can call the method:

    _engine.Execute("printNumber(25)");