ialex32x / unity-jsb

It brings Javascript runtime capability to Unity3D by integrating QuickJS.
MIT License
337 stars 43 forks source link

Example calling JS from C# #41

Closed FreakTheMighty closed 3 years ago

FreakTheMighty commented 3 years ago

Do you have any examples of calling a JS function with an argument from C#? I’d like to call something like a “main” method in a JavaScript method and pass in some context form c#. Any pointers would be much appreciated.

ialex32x commented 3 years ago

haven't supplied an easy method to archive it without delegate yet. there are some implemented but not so smooth ways:

  1. use EvalMain/EvalSource

    var fn = runtime.EvalSource<ScriptFunction>(...);
    fn.Invoke<RetrnType>(...);
  2. use native api like: Assets/jsb/Source/Unity/Editor/JSAssetPostprocessor.cs

  3. write a C# function to process

    
    void Run(ScriptFunction fn)
    {
    fn.Invoke<...>(...);
    }

// or a plain C# delegate void Run(Action fn) { fn(); }

```ts
csharp.Run(function () {...}); // the function will be automatically convert into ScriptFunction/Delegate in C#

I'll improve this part in the future.

FreakTheMighty commented 3 years ago

Thanks for the help @ialex32x . For others looking for a similar pattern here's what worked. I got a bit confused about the context that EvalSource was running in. Using require inside of the EvalSource gives me exactly what I'd like.

function run(core) {
    console.log(core);
}
exports.run = run;
runtime.EvalMain(entryFileName);
var func = runtime.GetMainContext().EvalSource<ScriptFunction>("require('main').run", "eval");
func.Invoke(new {});