2017年4月16日 星期日

讓 c++ 程式與 Javascript 做朋友

參考網址: https://nodejs.org/api/addons.html
node-gyp 是編譯 nodejs 模組的工具,用 c++ 語言寫模組的程式,經由node-gyp開發工具編譯成 .node 模組, javascript 程式則透過 require 將自訂模組引進加以運用:

1. 先安裝 node-gyp
    sudo npm install node-gyp -g

2. 用 JSON 語法,將目標(targets)需求(所要定義的模組名稱 target_name, 及原始c++檔案名稱 sources ),寫入 binding.gyp 檔案,例如:
// binding.gyp
    {  "targets": [
          {
                "target_name":  "hellocc",
                "sources":  [ "hello.cc" ]
          }                    
    ]}

3. 開始寫 c++ 程式,先引入標頭檔 node.h,所有取用 javascript 的部份,要使用node.h內所提供的方法及宣告, 最主要部份是編寫 Method這個c++程式,  而init()主要是將c++的程式模組名稱匯出,類似 module.exports = { } 這個動作,最後交由巨集 NODE_MODULE(hellocc,init) 將 javascript 模組名稱與c++程式相互連結.
 // 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;
          void Method(const FunctionCallbackInfo < Value >& args) {
                  Isolate* isolate = args.GetIsolate(); // 獲取輸出入參數的方法
                  args.GetReturnValue().Set(String::NewFromUtf8(isolate, " cc"));// 回傳字串 cc
          }
         void init(Local < Object > exports) {
                NODE_SET_METHOD(exports, "hello", Method); // exports.hello = Method
         }
        NODE_MODULE(hellocc, init)
   }

4. configure 讓 node-gyp 根據 binding.gyp 的內容,自動建立 node-gyp 編譯環境,並將檔案寫進 build 目錄內:
     node-gyp configure  

5. build 開始編譯 hello.cc,如果沒意外的話,將會產生 hellocc.node 模組
     node-gyp build

6. 寫一個  javascript 引進該模組使用,已經編譯好的模組通常放在 ./build/Release下面:
    // hello.js
    const addon = require('./build/Release/hellocc'); // 引入自訂模組
    console.log(addon.hello()); // 呼叫模組程式 hello( ), 並印出傳回來的字串

7. 執行 javascript, 印出  cc
    js hello.js

8. clean 刪除編譯環境,會將整個目錄 build 全部移除.
    node-gyp clean


   
 

沒有留言: