node.js调用C++函数的方法示例-创新互联
目前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 #includenamespace 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 & args struct void Add(const FunctionCallbackInfo & 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 num = Number::New(isolate, value); // Set the return value (using the passed in // FunctionCallbackInfo &) args.GetReturnValue().Set(num);} void Init(Local