🌐 Object Wrap
本教程是 Your First Project 的一种替代方案。它没有导出一个普通函数,而是演示如何使用 node-addon-api 的 ObjectWrap 类将 C++ 对象作为 JavaScript 对象公开。
🌐 This tutorial is an alternative to Your First Project. Instead of exporting a plain function, it demonstrates how to expose a C++ object as a JavaScript object using node-addon-api's ObjectWrap class.
在开始之前,确保你已经安装了所有必要的前置条件和工具,并阅读Node-API 项目结构解析以了解常见的项目布局和配置文件。
🌐 Before you start, make sure you've got all the necessary prerequisites and tools installed, and read Anatomy of a Node-API project to understand the common project layout and configuration files.
🌐 Creating a project
从 node-addon-examples 仓库中复制 Object Wrap 示例:
🌐 Copy the Object Wrap example from the node-addon-examples repository:
git clone https://github.com/nodejs/node-addon-examples.git
cp -r node-addon-examples/src/2-js-to-native-conversion/object-wrap-demo/node-addon-api object-wrap-demo
cd object-wrap-demo
npm install或者,手动设置项目:
🌐 Alternatively, set up the project manually:
mkdir object-wrap-demo
cd object-wrap-demo
npm init -y
npm install node-addon-api然后创建下面描述的源文件。一旦项目设置完成,验证一切是否正常运行:
🌐 Then create the source files described below. Once the project is set up, verify everything works:
npm test该项目的 binding.gyp 遵循标准格式(有关 binding.gyp 格式的完整说明以及 node-gyp 如何使用它,请参见 Node-API 项目的结构)。
🌐 The project's binding.gyp follows the standard format (see Anatomy of a Node-API project for a full explanation of the binding.gyp format and how node-gyp uses it).
🌐 src/object_wrap_demo.h and src/object_wrap_demo.cc
object_wrap_demo.h 和 object_wrap_demo.cc 是该项目的核心。napi.h 头文件来自 node-addon-api,并声明了表示 JavaScript 值的 C++ 类。
object_wrap_demo.cc 定义了 ObjectWrapDemo C++ 类:
- 构造函数 接收一个 JavaScript 字符串并将其存储在私有成员
_greeterName中。 Greet方法 接收一个 JavaScript 字符串,向标准输出打印两行,并返回最初传递给构造函数的值。GetClass静态方法 返回 Node-API 需要的类描述符,以便知道如何将调用从 JavaScript 调度到 C++ 方法。
Init 函数通过调用 ObjectWrapDemo::GetClass 来导出 ObjectWrapDemo 类。底部的 NODE_API_MODULE 宏确保在模块加载时调用 Init。
🌐 The Init function exports the ObjectWrapDemo class by calling ObjectWrapDemo::GetClass. The NODE_API_MODULE macro at the bottom ensures Init is called when the module is loaded.
binding.js 定义了一个 ObjectWrapDemo 类,它封装了本地二进制文件。当调用 new ObjectWrapDemo(value) 时,它会创建底层的 C++ 对象并将其存储为 _addonInstance。JavaScript 的 greet 方法会委托给 C++ 对象上的同名方法。
test_binding.js 展示了如何从 lib/binding.js 使用 ObjectWrapDemo JavaScript 类。请注意,调用 greet 会因为 C++ 代码中的 printf 调用而产生两行 stdout 输出作为副作用。
🌐 Conclusion
该项目展示了如何使用 ObjectWrap 将有状态的 C++ 对象暴露为 JavaScript 对象。接下来可以尝试的一些事情:
🌐 This project shows how to use ObjectWrap to expose a stateful C++ object as a JavaScript object. Some things to try next:
- 在你的调试器中运行
test_binding.js。逐步执行代码,并从调试器的角度观察 JavaScript 对象的样子。 - 修改
test_binding.js以直接引用已编译的二进制文件,而不是通过binding.js,并在调试器中观察差异。 - 扩展
object_wrap_demo.cc以在ObjectWrapDemo类上导出额外的方法或属性。