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] env: The environment that the API is invoked under.

  • [in] recv:传递给被调用函数的 this 值。

    ¥[in] recv: The this value passed to the called function.

  • [in] funcnapi_value 表示要调用的 JavaScript 函数。

    ¥[in] func: napi_value representing the JavaScript function to be invoked.

  • [in] argcargv 数组中的元素数。

    ¥[in] argc: The count of elements in the argv array.

  • [in] argvnapi_values 的数组,表示作为参数传递给函数的 JavaScript 值。

    ¥[in] argv: Array of napi_values representing JavaScript values passed in as arguments to the function.

  • [out] resultnapi_value 表示返回的 JavaScript 对象。

    ¥[out] result: napi_value representing the JavaScript object returned.

如果 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;