使用各种编程语言编写插件


【Writing addons in various programming languages】

Node-API 是一个 C 语言 API,它确保在不同的 Node.js 版本和不同的编译器级别之间的 ABI 稳定性。有了这种稳定性保证,就可以在 Node-API 上用其他编程语言编写插件。有关更多编程语言和引擎支持的详细信息,请参阅 语言和引擎绑定

【Node-API is a C API that ensures ABI stability across Node.js versions and different compiler levels. With this stability guarantee, it is possible to write addons in other programming languages on top of Node-API. Refer to language and engine bindings for more programming languages and engines support details.】

node-addon-api 是官方的 C++ 绑定,它提供了一种更高效的方式来编写调用 Node-API 的 C++ 代码。这个封装是一个仅包含头文件的库,提供了可内联的 C++ API。使用 node-addon-api 构建的二进制文件将依赖 Node.js 导出的基于 C 的 Node-API 函数符号。下面的代码示例展示了 node-addon-api 的用法:

Object obj = Object::New(env);
obj["foo"] = String::New(env, "bar"); 

上述 node-addon-api C++ 代码相当于以下基于 C 的 Node-API 代码:

【The above node-addon-api C++ code is equivalent to the following C-based Node-API code:】

napi_status status;
napi_value object, string;
status = napi_create_object(env, &object);
if (status != napi_ok) {
  napi_throw_error(env, ...);
  return;
}

status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &string);
if (status != napi_ok) {
  napi_throw_error(env, ...);
  return;
}

status = napi_set_named_property(env, object, "foo", string);
if (status != napi_ok) {
  napi_throw_error(env, ...);
  return;
} 

最终结果是,该插件仅使用导出的 C API。即使插件是用 C++ 编写的,它仍然能够享受由 C Node-API 提供的 ABI 稳定性带来的好处。

【The end result is that the addon only uses the exported C APIs. Even though the addon is written in C++, it still gets the benefits of the ABI stability provided by the C Node-API.】

在使用 node-addon-api 而不是 C API 时,首先使用 node-addon-api 的 API 文档

【When using node-addon-api instead of the C APIs, start with the API docs for node-addon-api.】

Node-API 资源 为刚开始使用 Node-API 和 node-addon-api 的开发者提供了出色的入门指导和建议。更多的媒体资源可以在 Node-API 媒体 页面找到。

【The Node-API Resource offers an excellent orientation and tips for developers just getting started with Node-API and node-addon-api. Additional media resources can be found on the Node-API Media page.】