目前nodejs调用c++主流的有两种方法,分别是addons和ffi
addons是nodejs官方的c++扩展实现方案,但是由于需要使用模版,并且要对v8引擎有一定的了解,入门门槛较高。
ffi是nodejs直接调用so库的一种实现,可以调用纯c的接口。
要想node.js调用C++的函数等,须先将C++代码编译成二进制的.node文件。node.js官方文档https://nodejs.org/dist/latest-v8.x/docs/api/addons.html中的C++ addons介绍了如何将C++的代码编译为二进制的.node文件。
一、步骤:
1.首先在项目目录进行npm install -g node-gyp下载node-gyp模块,配置环境参考https://github.com/nodejs/node-gyp
2.这是node官方文档中的例子
// 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")));
return;
}
// Check the argument types
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
// Perform the operation
double value = args[0]->NumberValue() + args[1]->NumberValue();
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 demo3.然后在项目目录下使用类似JSON的格式创建在项目顶层调用的文件binding.gyp文件,内容为
{
"targets": [
{
"target_name": "addon",
"sources": [ "addon.cc" ] }
]}4.在终端输入node-gyp configure命令生成一个build文件夹,然后输入node-gyp build命令生成编译addon.node文件
5.在node文件比如test.js文件中const addon=require(‘./build/Release/addon’)调用生成的模块
// test.js
const addon = require('./build/Release/addon');
console.log('This should be eight:', addon.add(3, 5));//结果为8









