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


¥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 导出的 Node-API C 函数的符号。以下代码片段是 node-addon-api 的一个示例:

¥node-addon-api is the official C++ binding that provides a more efficient way to write C++ code that calls Node-API. This wrapper is a header-only library that offers an inlinable C++ API. Binaries built with node-addon-api will depend on the symbols of the Node-API C-based functions exported by Node.js. The following code snippet is an example of 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.