napi_create_function
napi_status napi_create_function(napi_env env,
const char* utf8name,
size_t length,
napi_callback cb,
void* data,
napi_value* result); [in] env:调用该 API 时所处的环境。[in] utf8Name:函数的可选名称,使用 UTF8 编码。在 JavaScript 中可以通过新函数对象的name属性查看该名称。[in] length:utf8name的字节长度,如果它是以 null 结尾,则为NAPI_AUTO_LENGTH。[in] cb:当调用此函数对象时应调用的本地函数。napi_callback提供了更多详细信息。[in] 数据:用户提供的数据上下文。当函数稍后被调用时,这些数据将传回函数中。[out] result:表示新创建函数的 JavaScript 函数对象的napi_value。
如果 API 成功,则返回 napi_ok。
【Returns napi_ok if the API succeeded.】
此 API 允许插件作者在本地代码中创建一个函数对象。这是从 JavaScript 调用插件本地代码的主要机制。
【This API allows an add-on author to create a function object in native code. This is the primary mechanism to allow calling into the add-on's native code from JavaScript.】
新创建的函数在此调用之后不会自动从脚本中可见。相反,必须在任何对 JavaScript 可见的对象上显式设置一个属性,才能让脚本访问该函数。
【The newly created function is not automatically visible from script after this call. Instead, a property must be explicitly set on any object that is visible to JavaScript, in order for the function to be accessible from script.】
为了将一个函数作为插件模块导出的一部分,需要将新创建的函数设置在 exports 对象上。一个示例模块可能如下所示:
【In order to expose a function as part of the add-on's module exports, set the newly created function on the exports object. A sample module might look as follows:】
napi_value SayHello(napi_env env, napi_callback_info info) {
printf("Hello\n");
return NULL;
}
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_value fn;
status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn);
if (status != napi_ok) return NULL;
status = napi_set_named_property(env, exports, "sayHello", fn);
if (status != napi_ok) return NULL;
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) 鉴于以上代码,可以从 JavaScript 中使用附加组件,如下所示:
【Given the above code, the add-on can be used from JavaScript as follows:】
const myaddon = require('./addon');
myaddon.sayHello(); 传递给 require() 的字符串是 binding.gyp 中负责创建 .node 文件的目标名称。
【The string passed to require() is the name of the target in binding.gyp
responsible for creating the .node file.】
通过 data 参数传递给此 API 的任何非 NULL 数据都可以与生成的 JavaScript 函数(在 result 参数中返回)关联,并且可以在函数被垃圾回收时,通过将 JavaScript 函数和数据都传递给 napi_add_finalizer 来释放。
【Any non-NULL data which is passed to this API via the data parameter can
be associated with the resulting JavaScript function (which is returned in the
result parameter) and freed whenever the function is garbage-collected by
passing both the JavaScript function and the data to napi_add_finalizer.】
JavaScript Function 在 ECMAScript 语言规范的 部分函数对象 中有描述。
【JavaScript Functions are described in Section Function objects of the ECMAScript
Language Specification.】