napi_call_function
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:调用该 API 时所处的环境。[in] recv:传递给被调用函数的this值。[in] func:表示要调用的 JavaScript 函数的napi_value。[in] argc:argv数组中元素的数量。[in] argv:表示作为函数参数传入的 JavaScript 值的napi_values数组。[out] result:napi_value,表示返回的 JavaScript 对象。
如果 API 成功,则返回 napi_ok。
【Returns napi_ok if the API succeeded.】
此方法允许从本地插件调用 JavaScript 函数对象。这是从插件的本地代码回调到 JavaScript 的主要机制。对于在异步操作后调用 JavaScript 的特殊情况,请参阅 napi_make_callback。
【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.】
一个示例用例可能如下所示。考虑以下 JavaScript 代码片段:
【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;