C++ 插件#

插件是动态链接的共享对象,可以通过 require() 函数像普通的 Node.js 模块一样加载。插件在 JavaScript 和原生代码之间提供了一个外部函数接口。

实现插件有三种选择:

本文档的其余部分重点讨论后者,这需要了解多个组件和 API。

  • V8:Node.js 用于提供 JavaScript 实现的 C++ 库。它提供了创建对象、调用函数等的机制。V8 的 API 主要记录在 v8.h 头文件中(Node.js 源码树中的 deps/v8/include/v8.h),也可以在在线文档中查阅。

  • libuv:实现 Node.js 事件循环、工作线程及平台所有异步行为的 C 库。它还充当跨平台抽象库,在所有主要操作系统上提供简便的、类似 POSIX 的方式来执行常见的系统任务,如与文件系统、套接字、定时器和系统事件交互。libuv 还提供了类似于 POSIX 线程的线程抽象,供需要超越标准事件循环的更复杂的异步插件使用。插件作者应避免通过 I/O 或其他耗时任务阻塞事件循环,应通过 libuv 将工作卸载到非阻塞系统操作、工作线程或自定义的 libuv 线程中。

  • Node.js 内部库:Node.js 本身导出插件可以使用的 C++ API,其中最重要的是 node::ObjectWrap 类。

  • 其他静态链接库(包括 OpenSSL):这些库位于 Node.js 源码树的 deps/ 目录中。只有 libuv、OpenSSL、V8 和 zlib 符号是由 Node.js 特意重新导出的,并可被插件在不同程度上使用。有关更多信息,请参见链接到 Node.js 包含的库

以下所有示例均可下载,并可用作插件的起点。

Hello world#

这个“Hello world”示例是一个简单的 C++ 编写的插件,等同于以下 JavaScript 代码:

module.exports.hello = () => 'world';

首先,创建 hello.cc 文件

// hello.cc
#include <node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Value;

void Method(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(
      isolate, "world", NewStringType::kNormal).ToLocalChecked());
}

void Initialize(Local<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) // N.B.: no semi-colon, this is not a function

}  // namespace demo

在大多数平台上,以下 Makefile 可以帮助我们开始

NODEJS_DEV_ROOT ?= $(shell dirname "$(command -v node)")/..
CXXFLAGS = -std=c++23 -I$(NODEJS_DEV_ROOT)/include/node -fPIC -shared -Wl,-undefined,dynamic_lookup

hello.node: hello.cc
	$(CXX) $(CXXFLAGS) -o $@ $<

然后运行以下命令将编译并运行代码

$ make
$ node -p 'require("./hello.node").hello()'
world

要集成到 npm 生态系统中,请参阅构建一节。

上下文感知插件#

使用 NODE_MODULE() 定义的插件不能同时在多个上下文或多个线程中加载。

在某些环境中,Node.js 插件可能需要在多个上下文中多次加载。例如,Electron 运行时会在单个进程中运行多个 Node.js 实例。每个实例都有自己的 require() 缓存,因此当通过 require() 加载时,每个实例都需要原生插件正常工作。这意味着插件必须支持多次初始化。

可以使用宏 NODE_MODULE_INITIALIZER 构建上下文感知插件,它会展开为一个函数名,Node.js 在加载插件时会寻找该函数。因此,插件可以像下面的示例一样进行初始化。

using namespace v8;

extern "C" NODE_MODULE_EXPORT void
NODE_MODULE_INITIALIZER(Local<Object> exports,
                        Local<Value> module,
                        Local<Context> context) {
  /* Perform addon initialization steps here. */
}

另一种选择是使用宏 NODE_MODULE_INIT(),它也会构建一个上下文感知插件。与用于围绕给定插件初始化函数构建插件的 NODE_MODULE() 不同,NODE_MODULE_INIT() 用作此类初始化程序的声明,后跟函数体。

在调用 NODE_MODULE_INIT() 后的函数体内部,可以使用以下三个变量:

  • Local<Object> exports,
  • Local<Value> module,以及
  • Local<Context> context

构建上下文感知插件需要仔细管理全局静态数据,以确保稳定性和正确性。由于插件可能会被多次加载(甚至可能来自不同的线程),因此存储在插件中的任何全局静态数据都必须受到适当保护,并且不得包含对 JavaScript 对象的任何持久引用。原因是 JavaScript 对象仅在单个上下文中有效,在错误的上下文或创建它们的线程以外的线程中访问它们极可能导致崩溃。

上下文感知插件可以通过执行以下步骤来避免全局静态数据:

  • 定义一个类来保存每个插件实例的数据,该类具有以下形式的静态成员:
    static void DeleteInstance(void* data) {
      // Cast `data` to an instance of the class and delete it.
    }
    
  • 在插件初始化程序中堆分配该类的实例。这可以使用 new 关键字完成。
  • 调用 node::AddEnvironmentCleanupHook(),并将上面创建的实例和指向 DeleteInstance() 的指针传递给它。这将确保在环境销毁时删除该实例。
  • 将该类的实例存储在 v8::External 中,以及
  • v8::External 传递给所有暴露给 JavaScript 的方法,将其传给 v8::FunctionTemplate::New()v8::Function::New(),从而创建原生支持的 JavaScript 函数。v8::FunctionTemplate::New()v8::Function::New() 的第三个参数接受 v8::External,并通过 v8::FunctionCallbackInfo::Data() 方法使其在原生回调中可用。

这将确保每个插件实例的数据能够到达每个可从 JavaScript 调用的绑定。每个插件实例的数据也必须传递到插件可能创建的任何异步回调中。

以下示例演示了上下文感知插件的实现。

#include <node.h>

using namespace v8;

class AddonData {
 public:
  explicit AddonData(Isolate* isolate):
      call_count(0) {
    // Ensure this per-addon-instance data is deleted at environment cleanup.
    node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);
  }

  // Per-addon data.
  int call_count;

  static void DeleteInstance(void* data) {
    delete static_cast<AddonData*>(data);
  }
};

static void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {
  // Retrieve the per-addon-instance data.
  AddonData* data =
      reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());
  data->call_count++;
  info.GetReturnValue().Set((double)data->call_count);
}

// Initialize this addon to be context-aware.
NODE_MODULE_INIT(/* exports, module, context */) {
  Isolate* isolate = Isolate::GetCurrent();

  // Create a new instance of `AddonData` for this instance of the addon and
  // tie its life cycle to that of the Node.js environment.
  AddonData* data = new AddonData(isolate);

  // Wrap the data in a `v8::External` so we can pass it to the method we
  // expose.
  Local<External> external = External::New(isolate, data);

  // Expose the method `Method` to JavaScript, and make sure it receives the
  // per-addon-instance data we created above by passing `external` as the
  // third parameter to the `FunctionTemplate` constructor.
  exports->Set(context,
               String::NewFromUtf8(isolate, "method").ToLocalChecked(),
               FunctionTemplate::New(isolate, Method, external)
                  ->GetFunction(context).ToLocalChecked()).FromJust();
}
Worker 支持#

为了从多个 Node.js 环境(如主线程和 Worker 线程)加载,插件需要:

  • 成为一个 Node-API 插件。
  • 使用上述 NODE_MODULE_INIT() 声明为上下文感知。

为了支持 Worker 线程,插件需要清理它们在线程退出时可能分配的任何资源。这可以通过使用 AddEnvironmentCleanupHook() 函数来实现。

void AddEnvironmentCleanupHook(v8::Isolate* isolate,
                               void (*fun)(void* arg),
                               void* arg);

此函数添加一个在给定 Node.js 实例关闭前运行的钩子。如有必要,可以使用具有相同签名的 RemoveEnvironmentCleanupHook() 在运行前移除这些钩子。回调按后进先出 (LIFO) 的顺序运行。

如有必要,还有额外的 AddEnvironmentCleanupHook()RemoveEnvironmentCleanupHook() 重载版本,其中清理钩子接受一个回调函数。这可用于关闭异步资源,例如插件注册的任何 libuv 句柄。

以下 addon.cc 使用了 AddEnvironmentCleanupHook

// addon.cc
#include <node.h>
#include <assert.h>
#include <stdlib.h>

using node::AddEnvironmentCleanupHook;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;

// Note: In a real-world application, do not rely on static/global data.
static char cookie[] = "yum yum";
static int cleanup_cb1_called = 0;
static int cleanup_cb2_called = 0;

static void cleanup_cb1(void* arg) {
  Isolate* isolate = static_cast<Isolate*>(arg);
  HandleScope scope(isolate);
  Local<Object> obj = Object::New(isolate);
  assert(!obj.IsEmpty());  // assert VM is still alive
  assert(obj->IsObject());
  cleanup_cb1_called++;
}

static void cleanup_cb2(void* arg) {
  assert(arg == static_cast<void*>(cookie));
  cleanup_cb2_called++;
}

static void sanity_check(void*) {
  assert(cleanup_cb1_called == 1);
  assert(cleanup_cb2_called == 1);
}

// Initialize this addon to be context-aware.
NODE_MODULE_INIT(/* exports, module, context */) {
  Isolate* isolate = Isolate::GetCurrent();

  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);
  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);
  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);
}

通过以下方式在 JavaScript 中进行测试:

// test.js
require('./build/Release/addon');

构建#

编写完源代码后,必须将其编译为二进制 addon.node 文件。为此,在项目顶层创建一个名为 binding.gyp 的文件,使用类似 JSON 的格式描述模块的构建配置。该文件由专门用于编译 Node.js 插件的工具 node-gyp 使用。

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "hello.cc" ]
    }
  ]
}

node-gyp 实用程序的一个版本已与 Node.js 捆绑并作为 npm 的一部分分发。此版本不直接供开发人员使用,仅旨在支持使用 npm install 命令来编译和安装插件。希望直接使用 node-gyp 的开发人员可以使用命令 npm install -g node-gyp 安装它。有关更多信息,包括特定平台的要求,请参阅 node-gyp安装说明

创建 binding.gyp 文件后,使用 node-gyp configure 为当前平台生成适当的项目构建文件。这将在 build/ 目录中生成一个 Makefile(在 Unix 平台上)或一个 vcxproj 文件(在 Windows 上)。

接下来,调用 node-gyp build 命令来生成编译后的 addon.node 文件。它将被放入 build/Release/ 目录中。

当使用 npm install 安装 Node.js 插件时,npm 使用其自带的 node-gyp 版本来执行这一系列操作,按需为用户的平台生成编译后的插件版本。

构建完成后,可以通过指向已构建的 addon.node 模块使用 require() 在 Node.js 中使用该二进制插件。

// hello.js
const addon = require('./build/Release/addon');

console.log(addon.hello());
// Prints: 'world'

由于编译后的插件二进制文件的确切路径可能会因编译方式而异(例如,有时可能在 ./build/Debug/ 中),插件可以使用 bindings 包来加载编译后的模块。

虽然 bindings 包在定位插件模块方面的实现更为复杂,但它本质上使用的是类似于以下的 try…catch 模式:

try {
  return require('./build/Release/addon.node');
} catch (err) {
  return require('./build/Debug/addon.node');
}

链接到 Node.js 包含的库#

Node.js 使用 V8、libuv 和 OpenSSL 等静态链接库。所有插件都需要链接到 V8,也可以链接到任何其他依赖项。通常,这很简单,只需包含适当的 #include <...> 语句(例如 #include <v8.h>),node-gyp 就会自动定位适当的头文件。但是,有几点需要注意:

  • node-gyp 运行时,它会检测 Node.js 的特定发布版本,并下载完整的源代码 tarball 或仅下载头文件。如果下载了完整的源代码,插件将能够完全访问 Node.js 的全套依赖项。但是,如果仅下载了 Node.js 头文件,则只有 Node.js 导出的符号可用。

  • 可以使用指向本地 Node.js 源代码镜像的 --nodedir 标志运行 node-gyp。使用此选项,插件将能够访问全套依赖项。

使用 require() 加载插件#

编译后的插件二进制文件的文件扩展名是 .node(而不是 .dll.so)。require() 函数被编写为查找带有 .node 文件扩展名的文件,并将它们初始化为动态链接库。

调用 require() 时,通常可以省略 .node 扩展名,Node.js 仍然会找到并初始化插件。但有一点需要注意,Node.js 会首先尝试定位和加载恰好具有相同基本名称的模块或 JavaScript 文件。例如,如果与二进制文件 addon.node 同一目录下存在 addon.js 文件,则 require('addon') 会优先加载 addon.js 文件。

使用 import 加载插件#

稳定性:1.0 - 早期开发

你可以使用 --experimental-addon-modules 标志来启用对静态 import 和动态 import() 加载二进制插件的支持。

如果我们重用之前的 Hello World 示例,你可以这样做:

// hello.mjs
import myAddon from './hello.node';
// N.B.: import {hello} from './hello.node' would not work

console.log(myAddon.hello());
$ node --experimental-addon-modules hello.mjs
world

Node.js 原生抽象#

本文档中展示的每个示例都直接使用 Node.js 和 V8 API 来实现插件。V8 API 可能且确实从一个 V8 版本到下一个版本(以及一个主要 Node.js 版本到下一个版本)发生了巨大变化。随着每次变化,插件可能需要更新和重新编译才能继续运行。Node.js 的发布计划旨在最大限度地减少此类更改的频率和影响,但 Node.js 在确保 V8 API 的稳定性方面能做的事情很少。

Native Abstractions for Node.js (或 nan) 提供了一组建议插件开发人员使用的工具,以保持 V8 和 Node.js 过去和未来版本之间的兼容性。有关如何使用它的说明,请参阅 nan示例

Node-API#

稳定性:2 - 稳定

请参阅 使用 Node-API 开发 C/C++ 插件

插件示例#

以下是一些旨在帮助开发人员入门的示例插件。这些示例使用 V8 API。有关各种 V8 调用的帮助,请参阅在线 V8 参考,并参阅 V8 的 嵌入指南 (Embedder's Guide),以获取关于句柄、作用域、函数模板等所用概念的解释。

每个示例都使用以下 binding.gyp 文件:

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ]
    }
  ]
}

如果有多个 .cc 文件,只需将额外的文件名添加到 sources 数组即可:

"sources": ["addon.cc", "myexample.cc"]

一旦 binding.gyp 文件准备就绪,就可以使用 node-gyp 配置并构建示例插件:

node-gyp configure build

函数参数#

插件通常会暴露可在 Node.js 中运行的 JavaScript 访问的对象和函数。当从 JavaScript 调用函数时,输入参数和返回值必须映射到 C/C++ 代码或从中映射出来。

以下示例演示了如何读取从 JavaScript 传递的函数参数以及如何返回结果:

// addon.cc
#include <node.h>

namespace demo {

using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

// This is the implementation of the "add" method
// Input arguments are passed using the
// const FunctionCallbackInfo<Value>& args struct
void Add(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  // Check the number of arguments passed.
  if (args.Length() < 2) {
    // Throw an Error that is passed back to JavaScript
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate,
                            "Wrong number of arguments").ToLocalChecked()));
    return;
  }

  // Check the argument types
  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate,
                            "Wrong arguments").ToLocalChecked()));
    return;
  }

  // Perform the operation
  double value =
      args[0].As<Number>()->Value() + args[1].As<Number>()->Value();
  Local<Number> num = Number::New(isolate, value);

  // Set the return value (using the passed in
  // FunctionCallbackInfo<Value>&)
  args.GetReturnValue().Set(num);
}

void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "add", Add);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

}  // namespace demo

编译后,可以在 Node.js 中引入并使用该示例插件:

// test.js
const addon = require('./build/Release/addon');

console.log('This should be eight:', addon.add(3, 5));

回调#

在插件中,将 JavaScript 函数传递给 C++ 函数并在其中执行它们是常见的做法。以下示例说明了如何调用此类回调:

// addon.cc
#include <node.h>

namespace demo {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Null;
using v8::Object;
using v8::String;
using v8::Value;

void RunCallback(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  Local<Context> context = isolate->GetCurrentContext();
  Local<Function> cb = Local<Function>::Cast(args[0]);
  const unsigned argc = 1;
  Local<Value> argv[argc] = {
      String::NewFromUtf8(isolate,
                          "hello world").ToLocalChecked() };
  cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
}

void Init(Local<Object> exports, Local<Object> module) {
  NODE_SET_METHOD(module, "exports", RunCallback);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

}  // namespace demo

此示例使用了 Init() 的双参数形式,它接收完整的 module 对象作为第二个参数。这允许插件用单个函数完全覆盖 exports,而不是将函数添加为 exports 的属性。

要测试它,请运行以下 JavaScript:

// test.js
const addon = require('./build/Release/addon');

addon((msg) => {
  console.log(msg);
// Prints: 'hello world'
});

在此示例中,回调函数是同步调用的。

对象工厂#

插件可以在 C++ 函数内部创建并返回新对象,如下例所示。创建并返回了一个带有 msg 属性的对象,该属性回显传递给 createObject() 的字符串:

// addon.cc
#include <node.h>

namespace demo {

using v8::Context;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  Local<Context> context = isolate->GetCurrentContext();

  Local<Object> obj = Object::New(isolate);
  obj->Set(context,
           String::NewFromUtf8(isolate,
                               "msg").ToLocalChecked(),
                               args[0]->ToString(context).ToLocalChecked())
           .FromJust();

  args.GetReturnValue().Set(obj);
}

void Init(Local<Object> exports, Local<Object> module) {
  NODE_SET_METHOD(module, "exports", CreateObject);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

}  // namespace demo

在 JavaScript 中测试:

// test.js
const addon = require('./build/Release/addon');

const obj1 = addon('hello');
const obj2 = addon('world');
console.log(obj1.msg, obj2.msg);
// Prints: 'hello world'

函数工厂#

另一个常见的场景是创建包装 C++ 函数的 JavaScript 函数,并将这些函数返回给 JavaScript:

// addon.cc
#include <node.h>

namespace demo {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void MyFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(
      isolate, "hello world").ToLocalChecked());
}

void CreateFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  Local<Context> context = isolate->GetCurrentContext();
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();

  // omit this to make it anonymous
  fn->SetName(String::NewFromUtf8(
      isolate, "theFunction").ToLocalChecked());

  args.GetReturnValue().Set(fn);
}

void Init(Local<Object> exports, Local<Object> module) {
  NODE_SET_METHOD(module, "exports", CreateFunction);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

}  // namespace demo

测试:

// test.js
const addon = require('./build/Release/addon');

const fn = addon();
console.log(fn());
// Prints: 'hello world'

包装 C++ 对象#

也可以包装 C++ 对象/类,允许使用 JavaScript new 运算符创建新实例:

// addon.cc
#include <node.h>
#include "myobject.h"

namespace demo {

using v8::Local;
using v8::Object;

void InitAll(Local<Object> exports) {
  MyObject::Init(exports);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)

}  // namespace demo

然后,在 myobject.h 中,包装类继承自 node::ObjectWrap

// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <node.h>
#include <node_object_wrap.h>

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Local<v8::Object> exports);

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);

  double value_;
};

}  // namespace demo

#endif

myobject.cc 中,实现要暴露的各种方法。在以下代码中,方法 plusOne() 通过将其添加到构造函数的原型中而被暴露:

// myobject.cc
#include "myobject.h"

namespace demo {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::ObjectTemplate;
using v8::String;
using v8::Value;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Local<Object> exports) {
  Isolate* isolate = Isolate::GetCurrent();
  Local<Context> context = isolate->GetCurrentContext();

  Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);
  addon_data_tpl->SetInternalFieldCount(1);  // 1 field for the MyObject::New()
  Local<Object> addon_data =
      addon_data_tpl->NewInstance(context).ToLocalChecked();

  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New, addon_data);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);

  Local<Function> constructor = tpl->GetFunction(context).ToLocalChecked();
  addon_data->SetInternalField(0, constructor);
  exports->Set(context, String::NewFromUtf8(
      isolate, "MyObject").ToLocalChecked(),
      constructor).FromJust();
}

void MyObject::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  Local<Context> context = isolate->GetCurrentContext();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ?
        0 : args[0]->NumberValue(context).FromMaybe(0);
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons =
        args.Data().As<Object>()->GetInternalField(0)
            .As<Value>().As<Function>();
    Local<Object> result =
        cons->NewInstance(context, argc, argv).ToLocalChecked();
    args.GetReturnValue().Set(result);
  }
}

void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
  obj->value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}

}  // namespace demo

要构建此示例,必须将 myobject.cc 文件添加到 binding.gyp 中:

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [
        "addon.cc",
        "myobject.cc"
      ]
    }
  ]
}

测试它:

// test.js
const addon = require('./build/Release/addon');

const obj = new addon.MyObject(10);
console.log(obj.plusOne());
// Prints: 11
console.log(obj.plusOne());
// Prints: 12
console.log(obj.plusOne());
// Prints: 13

包装对象的析构函数将在对象被垃圾回收时运行。为了进行析构函数测试,可以使用命令行标志来强制执行垃圾回收。这些标志由底层 V8 JavaScript 引擎提供。它们随时可能更改或删除。Node.js 或 V8 不记录这些标志,且不应在测试之外使用它们。

在进程或工作线程关闭期间,JS 引擎不会调用析构函数。因此,用户有责任跟踪这些对象并确保正确销毁以避免资源泄漏。

包装对象的工厂#

或者,可以使用工厂模式来避免显式使用 JavaScript new 运算符创建对象实例:

const obj = addon.createObject();
// instead of:
// const obj = new addon.Object();

首先,在 addon.cc 中实现 createObject() 方法:

// addon.cc
#include <node.h>
#include "myobject.h"

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo<Value>& args) {
  MyObject::NewInstance(args);
}

void InitAll(Local<Object> exports, Local<Object> module) {
  MyObject::Init();

  NODE_SET_METHOD(module, "exports", CreateObject);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)

}  // namespace demo

myobject.h 中,添加静态方法 NewInstance() 以处理对象的实例化。此方法代替了在 JavaScript 中使用 new

// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <node.h>
#include <node_object_wrap.h>

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init();
  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
  static v8::Global<v8::Function> constructor;
  double value_;
};

}  // namespace demo

#endif

myobject.cc 中的实现与之前的示例类似:

// myobject.cc
#include <node.h>
#include "myobject.h"

namespace demo {

using node::AddEnvironmentCleanupHook;
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Global;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

// Warning! This is not thread-safe, this addon cannot be used for worker
// threads.
Global<Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init() {
  Isolate* isolate = Isolate::GetCurrent();
  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);

  Local<Context> context = isolate->GetCurrentContext();
  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());

  AddEnvironmentCleanupHook(isolate, [](void*) {
    constructor.Reset();
  }, nullptr);
}

void MyObject::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  Local<Context> context = isolate->GetCurrentContext();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ?
        0 : args[0]->NumberValue(context).FromMaybe(0);
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    Local<Object> instance =
        cons->NewInstance(context, argc, argv).ToLocalChecked();
    args.GetReturnValue().Set(instance);
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  const unsigned argc = 1;
  Local<Value> argv[argc] = { args[0] };
  Local<Function> cons = Local<Function>::New(isolate, constructor);
  Local<Context> context = isolate->GetCurrentContext();
  Local<Object> instance =
      cons->NewInstance(context, argc, argv).ToLocalChecked();

  args.GetReturnValue().Set(instance);
}

void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
  obj->value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}

}  // namespace demo

再次强调,要构建此示例,必须将 myobject.cc 文件添加到 binding.gyp 中:

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [
        "addon.cc",
        "myobject.cc"
      ]
    }
  ]
}

测试它:

// test.js
const createObject = require('./build/Release/addon');

const obj = createObject(10);
console.log(obj.plusOne());
// Prints: 11
console.log(obj.plusOne());
// Prints: 12
console.log(obj.plusOne());
// Prints: 13

const obj2 = createObject(20);
console.log(obj2.plusOne());
// Prints: 21
console.log(obj2.plusOne());
// Prints: 22
console.log(obj2.plusOne());
// Prints: 23

传递包装对象#

除了包装和返回 C++ 对象外,还可以通过使用 Node.js 辅助函数 node::ObjectWrap::Unwrap 解包来传递包装对象。以下示例展示了一个可以接受两个 MyObject 对象作为输入参数的 add() 函数:

// addon.cc
#include <node.h>
#include <node_object_wrap.h>
#include "myobject.h"

namespace demo {

using v8::Context;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo<Value>& args) {
  MyObject::NewInstance(args);
}

void Add(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  Local<Context> context = isolate->GetCurrentContext();

  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
      args[0]->ToObject(context).ToLocalChecked());
  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
      args[1]->ToObject(context).ToLocalChecked());

  double sum = obj1->value() + obj2->value();
  args.GetReturnValue().Set(Number::New(isolate, sum));
}

void InitAll(Local<Object> exports) {
  MyObject::Init();

  NODE_SET_METHOD(exports, "createObject", CreateObject);
  NODE_SET_METHOD(exports, "add", Add);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)

}  // namespace demo

myobject.h 中,添加了一个新的公共方法,以允许在解包对象后访问私有值:

// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <node.h>
#include <node_object_wrap.h>

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init();
  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
  inline double value() const { return value_; }

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static v8::Global<v8::Function> constructor;
  double value_;
};

}  // namespace demo

#endif

myobject.cc 的实现与之前的版本类似:

// myobject.cc
#include <node.h>
#include "myobject.h"

namespace demo {

using node::AddEnvironmentCleanupHook;
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Global;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

// Warning! This is not thread-safe, this addon cannot be used for worker
// threads.
Global<Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init() {
  Isolate* isolate = Isolate::GetCurrent();
  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  Local<Context> context = isolate->GetCurrentContext();
  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());

  AddEnvironmentCleanupHook(isolate, [](void*) {
    constructor.Reset();
  }, nullptr);
}

void MyObject::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  Local<Context> context = isolate->GetCurrentContext();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ?
        0 : args[0]->NumberValue(context).FromMaybe(0);
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    Local<Object> instance =
        cons->NewInstance(context, argc, argv).ToLocalChecked();
    args.GetReturnValue().Set(instance);
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  const unsigned argc = 1;
  Local<Value> argv[argc] = { args[0] };
  Local<Function> cons = Local<Function>::New(isolate, constructor);
  Local<Context> context = isolate->GetCurrentContext();
  Local<Object> instance =
      cons->NewInstance(context, argc, argv).ToLocalChecked();

  args.GetReturnValue().Set(instance);
}

}  // namespace demo

测试它:

// test.js
const addon = require('./build/Release/addon');

const obj1 = addon.createObject(10);
const obj2 = addon.createObject(20);
const result = addon.add(obj1, obj2);

console.log(result);
// Prints: 30