nodejs在Windows下c++插件編譯

nodejs在Windows下c++插件編譯


如需轉載請標明出處:http://blog.csdn.net/itas109
QQ技術交流羣:129518033

環境:

OS : windows 7 64bit

nodejs : 10.153

node-gyp : 6.0.0

編譯器 :vs2017

Python : 2.7.15

1. 安裝nodejs

略過

2.安裝node-gyp

參考https://www.npmjs.com/package/node-gyp

Windows下:

# 安裝
npm install -g node-gyp

查看node-gyp的版本

node-gyp -v

3.安裝Python及 Visual Studio

3.1 自動安裝

以管理員方式運行cmd,並執行

npm install --global --production windows-build-tools

在這裏插入圖片描述

參考:windows-build-tools

3.2 手動安裝

安裝vs2017和python2.7

配置python

npm config set python /path/to/executable/python2.7

配置c++構建工具

npm config set msvs_version 2017

4.編寫測試代碼

4.1 編寫hello.cc

#include <node.h>
#include <v8.h>

using namespace v8;

void Method(const v8::FunctionCallbackInfo<Value>& args) 
{
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}

void Init(Handle<Object> exports) 
{
  Isolate* isolate = Isolate::GetCurrent();
  exports->Set(String::NewFromUtf8(isolate, "hello"),
      FunctionTemplate::New(isolate, Method)->GetFunction());

}

NODE_MODULE(hello, Init)

注意,所有的 Node.js 插件必須導出一個如下模式的初始化函數:

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

NODE_MODULE 後面沒有分號,因爲它不是一個函數(詳見 node.h)。

module_name 必須匹配最終的二進制文件名(不包括 .node 後綴)。

在 hello.cc 示例中,初始化函數是 Init,插件模塊名是 addon。

4.2 編寫構建文件binding.gyp

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

4.3 編譯.node模塊

node-gyp configure --debug build

–debug參數表示生成debug文件

4.4 編寫hello.js

//hello.js

var addon = require('./build/Debug/hello.node');

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

require的路徑需要和3.3中編譯出來的路徑一致

4.5 運行

node hello.js

4.6 結果

$ node hello.js 
world

在這裏插入圖片描述

覺得文章對你有幫助,可以掃描二維碼捐贈給博主,謝謝!
在這裏插入圖片描述
如需轉載請標明出處:http://blog.csdn.net/itas109
QQ技術交流羣:129518033


License

License under CC BY-NC-ND 4.0: 署名-非商業使用-禁止演繹


Reference:
1.http://nodejs.cn/api/addons.html
2.https://www.jianshu.com/p/8a9f4304557c
3.https://www.npmjs.com/package/node-gyp
4.https://github.com/felixrieseberg/windows-build-tools

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章