Node.js C++ 扩展开发的三种主流方案:原生API、v8异步与SWIG
本文详细解析Node.js中C++组件开发的三种核心路径。首先对比原生v8 API与SWIG工具的优劣,随后深入讲解纯JS模块、基于v8 API的同步及异步(uv_queue_work)组件实现,最后介绍利用SWIG框架处理C++类型映射与多语言支持的方法,涵盖从环境配置到代码编写的完整流程。
v8 API与SWIG框架对比
在开始具体实现之前,有必要先厘清使用原生v8 API与借助SWIG框架进行开发的区别。
第一种方式是直接调用v8 API,这是官方提供的原生手段。其优势在于功能强大且完善,但缺点也很明显:开发者必须深入熟悉v8 API,编码过程较为繁琐。此外,这种方式与JavaScript强绑定,难以直接支持其他脚本语言。
第二种方式采用SWIG框架,这是一款第三方的强大组件开发工具。它支持为Python、Lua、JavaScript等多种常见脚本语言自动生成C++组件包装代码。使用SWIG时,开发者只需编写C++代码和配置文件即可,无需掌握各脚本语言特定的组件开发框架。然而,SWIG不支持JavaScript回调,且文档与示例代码相对匮乏,用户群体较小。
纯JS实现Node.js组件
一、纯JavaScript实现Node.js组件 (1)进入helloworld目录,执行npm init命令初始化package.json文件,各项配置保持默认即可。
(2)创建组件的核心实现文件index.js,参考示例:
module.exports.Hello = function(name) {
console.log('Hello ' + name);
}
(3)在helloworld目录的上级目录中执行npm install ./helloworld,此时helloworld模块将被安装至node_modules目录。 (4)编写调用组件的测试代码:
var m = require('helloworld');
m.Hello('zhangsan');
//输出: Hello zhangsan
v8 API同步组件实现
二、使用v8 API实现JS组件——同步模式 (1)首先编写binding.gyp构建配置文件,示例如下:
{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cpp" ]
}
]
}
(2)接着编写C++组件实现文件hello.cpp,参考示例:
#include <node.h>
namespace cpphello {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void Foo(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World"));
}
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "foo", Foo);
}
NODE_MODULE(cpphello, Init)
}
(3)执行编译操作。
node-gyp configure
node-gyp build
./build/Release/目录下会生成hello.node模块。
(4)编写用于测试的JavaScript代码。
const m = require('./build/Release/hello')
console.log(m.foo()); //输出 Hello World
(5)添加package.json文件以支持模块安装,示例配置如下:
{
"name": "hello",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "node test.js"
},
"author": "",
"license": "ISC"
}
(6)将组件安装至node_modules目录。
进入组件目录的上级目录,执行命令:npm install ./helloc(注:helloc为组件所在目录名称)。 这会将hello模块安装到当前目录下的node_modules中,测试代码写法如下:
var m = require('hello');
console.log(m.foo());
v8 API异步组件实现
三、使用v8 API实现JS组件——异步模式 上述案例均为同步组件,其中foo()为同步函数,调用者必须等待foo()执行完毕才能继续后续操作。当foo()涉及IO耗时操作时,采用异步版本的foo()能有效减少阻塞等待,从而提升整体系统性能。
实现异步组件的关键在于利用libuv提供的uv_queue_work API。除了主体代码hello.cpp和用户调用代码外,其余部分与前述同步模式的demo保持一致。
hello.cpp实现如下:
/*
* Node.js cpp Addons demo: async call and call back.
* gcc 4.8.2
* author:cswuyg
* Date:2016.02.22
* */
#include <iostream>
#include <node.h>
#include <uv.h>
#include <sstream>
#include <unistd.h>
#include <pthread.h>
namespace cpphello {
using v8::FunctionCallbackInfo;
using v8::Function;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::Value;
using v8::Exception;
using v8::Persistent;
using v8::HandleScope;
using v8::Integer;
using v8::String;
// async task
struct MyTask{
uv_work_t work;
int a{0};
int b{0};
int output{0};
unsigned long long work_tid{0};
unsigned long long main_tid{0};
Persistent<Function> callback;
};
// async function
void query_async(uv_work_t* work) {
MyTask* task = (MyTask*)work->data;
task->output = task->a + task->b;
task->work_tid = pthread_self();
usleep(1000 * 1000 * 1); // 1 second
}
// async complete callback
void query_finish(uv_work_t* work, int status) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope handle_scope(isolate);
MyTask* task = (MyTask*)work->data;
const unsigned int argc = 3;
std::stringstream stream;
stream << task->main_tid;
std::string main_tid_s{stream.str()};
stream.str("");
stream << task->work_tid;
std::string work_tid_s{stream.str()};
Local<Value> argv[argc] = {
Integer::New(isolate, task->output),
String::NewFromUtf8(isolate, main_tid_s.c_str()),
String::NewFromUtf8(isolate, work_tid_s.c_str())
};
Local<Function>::New(isolate, task->callback)->Call(isolate->GetCurrentContext()->Global(), argc, argv);
task->callback.Reset();
delete task;
}
// async main
void async_foo(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope handle_scope(isolate);
if (args.Length() != 3) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "arguments num : 3")));
return;
}
if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "arguments error")));
return;
}
MyTask* my_task = new MyTask;
my_task->a = args[0]->ToInteger()->Value();
my_task->b = args[1]->ToInteger()->Value();
my_task->callback.Reset(isolate, Local<Function>::Cast(args[2]));
my_task->work.data = my_task;
my_task->main_tid = pthread_self();
uv_loop_t *loop = uv_default_loop();
uv_queue_work(loop, &my_task->work, query_async, query_finish);
}
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "foo", async_foo);
}
NODE_MODULE(cpphello, Init)
}
异步逻辑的核心思路非常清晰:实现一个工作函数、一个完成回调函数,以及一个用于跨线程传输数据的结构体,最后调用uv_queue_work即可。主要难点在于对v8数据结构和API的熟练掌握。
test.js测试代码如下:
// test helloUV module
'use strict';
const m = require('helloUV')
m.foo(1, 2, (a, b, c)=>{
console.log('finish job:' + a);
console.log('main thread:' + b);
console.log('work thread:' + c);
});
/*
output:
finish job:3
main thread:139660941432640
work thread:139660876334848
*/
SWIG框架封装组件
四、利用SWIG-JavaScript实现Node.js组件 本节介绍如何使用SWIG框架编写Node.js组件。
(1)首先准备好C++组件的实现文件:*.h和*.cpp。
示例代码:
namespace a {
class A{
public:
int add(int a, int y);
};
int add(int x, int y);
}
(2)编写*.i接口文件,用于生成SWIG的包装C++文件。 示例配置:
/* File : IExport.i */
%module my_mod
%include "typemaps.i"
%include "std_string.i"
%include "std_vector.i"
%{
#include "export.h"
%}
%apply int *OUTPUT { int *result, int* xx};
%apply std::string *OUTPUT { std::string* result, std::string* yy };
%apply std::string &OUTPUT { std::string& result };
%include "export.h"
namespace std {
%template(vectori) vector<int>;
%template(vectorstr) vector<std::string>;
};
上述代码中的%apply指令表明,代码中的int* result、int* xx、std::string* result、std::string* yy以及std::string& result属于输出参数描述,这涉及typemap类型映射机制。 在C++函数参数中,若指针参数被标记为返回值(通过*.i文件中的OUTPUT指定),SWIG会将其处理为JS函数的返回值。若存在多个此类指针,JS函数的返回值将是一个列表。 %template(vectori) vector<int> 表示为JS定义了一个名为vectori的类型,这通常用于C++函数将vector<int>作为参数或返回值的情况。在编写JS代码时,需要用到该类型。 (3)编写binding.gyp文件,用于通过node-gyp进行编译。 (4)生成包装C++文件。生成时需注意v8版本信息,示例命令:swig -javascript -node -c++ -DV8_VERSION=0x040599 example.i (5)编译并测试。 此方法的难点在于STL类型和自定义类型的使用,官方相关文档较少。关于SWIG-JavaScript对std::vector和std::string的封装使用,可参考我的练习代码,重点在于*.i文件的实现。
Node与Lua组件开发对比
五、其他对比分析 在使用v8 API实现Node.js组件时,可以发现其与实现Lua组件存在相似之处:Lua使用状态机,而Node.js使用Isolate。
在Node中导出对象时,需要实现一个构造函数,为其添加“成员函数”,最后将构造函数导出为类名。而在Lua中导出对象时,也需要实现一个创建对象的工厂函数,将“成员函数”添加到table中,最后导出该工厂函数。
由于Node的JS脚本支持new关键字,而Lua不支持,因此Lua仅提供对象工厂用于创建对象,而Node既可以提供对象工厂,也可以提供类封装。 以上即为本文的全部内容,希望能为读者的学习提供帮助。
在 NestJS 中使用管道验证数据与守卫控制访问权限
2026-11-05 12:43:41
Node.js后端生成高强度随机字符串的方法
2026-11-04 16:29:54
Node.js环境中怎么使用axios或http模块发送GET请求
2026-11-03 21:57:15
Node.js环境下怎么实现JS反混淆自动化?常用库与CLI工具推荐
2026-11-03 21:15:54
解决JS逆向常见报错:缺少DOM环境导致代码运行失败
2026-11-03 20:41:59
