Calling Javascript function from C++

The BabylonNative examples show how Javascript can call back to C++. I would like to initiate a render operation from C++. Is there an example of how to use napi to call a Javascript function, as it relates to the BabylonNative environment.

The only platform I care about in this case is Linux.

Hi mburbidg,

There are a couple of different places where we do this in different ways; for example, in the NativeCapture plugin, we put capture data into a JS object and tell JavaScript listeners about it via a callback. Basically, you just need a Napi::FunctionReference to whatever function it is you want to call, which you can get either by having it passed to you (as is done in the callback example) or by grabbing it directly if you know its name. Here’s a rather weird-looking but concise example of the latter:

// Where info is a const Napi::CallbackInfo&, but you could also get an Env any other way
info.Env().Global().Get("someObjectInTheGlobalScope").As<Napi::Object>().Get("someFunction").As<Napi::Function>().Call({Napi::Object::New(info.Env())});

Do either of these examples help with your particular scenario?

That helps. If the function is a global function, can I do the following?

env.Global().Get(“someFunction”).AsNapi::Function().Call({Napi::Object::New(info.Env())});

Yes, I think that should work. As long as you have a Napi::Function or Napi::FunctionReference to your function, you should be able to call it from that.