microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.74k stars 148 forks source link

How to execute/call objects via interop? #508

Closed somecodingwitch closed 1 year ago

somecodingwitch commented 1 year ago

Let's supposed I have an interop object, a result from the engine.EvaluateScript(...) method as an object. Now let's suppose that result is a JavaScript Function, I have that in C# now.

How can I:

For example, in Jint I can do:

var myFunction = engine.Evaluate(...);
engine.Call(myFunction, ...);
ClearScriptLib commented 1 year ago

Hi @victoriaquasar,

Execute the function in the engine using the object variable that I got?

Script objects are instances of the ScriptObject class, which has methods such as InvokeAsFunction:

engine.AddHostType(typeof(Console));
var func = (ScriptObject)engine.Evaluate("(function(x) { Console.WriteLine(x); })");
func.InvokeAsFunction("Hello, world!");

You can also use C#'s dynamic type:

engine.AddHostType(typeof(Console));
dynamic func = engine.Evaluate("(function(x) { Console.WriteLine(x); })");
func("Hello, world!");

Or pass the object back to the engine then execute it as function?

No problem at all:

engine.Execute("function invoke(x) { x(...Array.from(arguments).slice(1)); }");
engine.Script.invoke(func, "Hello, world!");

Good luck!

somecodingwitch commented 1 year ago

Thanks!