天天看点

在 Node.js 中使用C++

这几天在看 Node.js 的官方文档,看到了 C++ 插件部分,由于很久没有接触 C/C++ 了,看起来着实吃力,决定写一个 Hello World 后跳过该部分。

在 Node.js 上使用 C++,需要用 node-gyp 工具对 C++ 文件进行编译,所以首先要安装 node-gyp :

然后在项目目录下写一个 hello.cc 文件:

#include <node.h>

namespace demo{
    using v8::FunctionCallbackInfo;
    using v8::Isolate;
    using v8::Local;
    using v8::Object;
    using v8::String;
    using v8::Value;
    using v8::Number;

    // Method1 实现一个 输出"hello world ONE !" 的方法
    void Method1(const FunctionCallbackInfo<Value>& args){
        Isolate* isolate = args.GetIsolate();
        args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world ONE !"));
    }

    // Method2 实现一个 加一 的方法
    void Method2(const FunctionCallbackInfo<Value>& args){
        Isolate* isolate = args.GetIsolate();
        // 获取参数,js Number 类型转换成 v8 Number 类型 
        Local<Number> value = Local<Number>::Cast(args[]); 
        double num = value->NumberValue() + ;

        // double 转 char*,这里我不知道有没有其他办法
        char buf[] = {};
        sprintf(buf,"%f", num);

        args.GetReturnValue().Set(String::NewFromUtf8(isolate, buf));
    }

    void init(Local<Object> exports){
        NODE_SET_METHOD(exports, "hello1", Method1);
        NODE_SET_METHOD(exports, "addOne", Method2);
    }

    NODE_MODULE(addon, init)
}
           

按照我的理解,Method1、Method2就是我们为这个 C++ 插件提供的功能,其参数是个回调函数,args.GetReturnValue().Set() 方法应该是输出了这个函数的返回值,也就是在 js 中调用这个函数得到相应返回值。

Node.js插件必须导出一个具有如下模式的初始化函数:

void Initialize(Local<Object> exports);
NODE_MODULE(module_name, Initialize)
           

官网上说 NODE_MODULE 后面没有分号,因为他不是一个函数(一脸懵逼)。在上面的 hello.cc 文件中,初始化函数是 init,插件模块名为 addon。NODE_SET_METHOD 是对插件输出的函数命名。

接下来就要对这个文件编译成 Node.js 的插件了,首先需要一个配置文件。在项目目录中建立一个 binding.gyp 的文件,这个文件会被 node-gyp 使用到:

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

然后在项目目录下使用 node-gyp configure 命令,这样在 Windows 上会得到一个 build 文件夹:

build
    │  addon.vcxproj
    │  addon.vcxproj.filters
    │  binding.sln
    │  config.gypi
    │
    └─Release
        └─obj
            └─addon
                └─addon.tlog
           

然后继续使用 node-gyp build 命令,成功后在 build/Release 文件夹下有个 addon.node 的二进制文件,这就是最终得到的 C++ 插件,可以在 js 中调用下:

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

console.log(addon.hello1());
console.log(addon.addOne());
           

输出:

hello world ONE !

           

到此一个 Node.js 中 C++ 插件的 Hello World 结束。

继续阅读