napi_call_function
functionv1js_native_api.hThis method allows a JavaScript function object to be called from a native add-on. This is the primary mechanism of calling back _from_ the add-on's native code _into_ JavaScript.
NAPI_EXTERN napi_status napi_call_function(napi_env env,
napi_value recv,
napi_value func,
size_t argc,
const napi_value* argv,
napi_value* result);
[in] env: The environment that the API is invoked under.[in] recv: Thethisvalue passed to the called function.[in] func:napi_valuerepresenting the JavaScript function to be invoked.[in] argc: The count of elements in theargvarray.[in] argv: Array ofnapi_valuesrepresenting JavaScript values passed in as arguments to the function.[out] result:napi_valuerepresenting the JavaScript object returned.
Returns napi_ok if the API succeeded.
This method allows a JavaScript function object to be called from a native
add-on. This is the primary mechanism of calling back from the add-on's
native code into JavaScript. For the special case of calling into JavaScript
after an async operation, see napi_make_callback.
A sample use case might look as follows. Consider the following JavaScript snippet:
function AddTwo(num) {
return num + 2;
}
global.AddTwo = AddTwo;
Then, the above function can be invoked from a native add-on using the following code:
// Get the function named "AddTwo" on the global object
napi_value global, add_two, arg;
napi_status status = napi_get_global(env, &global);
if (status != napi_ok) return;
status = napi_get_named_property(env, global, "AddTwo", &add_two);
if (status != napi_ok) return;
// const arg = 1337
status = napi_create_int32(env, 1337, &arg);
if (status != napi_ok) return;
napi_value* argv = &arg;
size_t argc = 1;
// AddTwo(arg);
napi_value return_val;
status = napi_call_function(env, global, add_two, argc, argv, &return_val);
if (status != napi_ok) return;
// Convert the result back to a native type
int32_t result;
status = napi_get_value_int32(env, return_val, &result);
if (status != napi_ok) return;