Node.js C++擴充實現

來源:互聯網
上載者:User

標籤:

因為有了Node.js,JavaScript可以被用於服務端編程。通過各種擴充,Node.js可以變得非常強大。今天分享下怎樣用C++建立Node.js擴充。

參考原文:Making Dynamsoft Barcode SDK an Addon for Node.js

搭建Nodejs開發環境

要構建擴充,需要安裝node-gyp:

npm install -g node-gyp

這個庫裡麵包涵了JavaScript v8引擎所需要的標頭檔以及依賴庫。

建立一個C/C++檔案dbr.cc以及設定檔binding.gyp。開啟設定檔,在裡面加入副檔名和原始碼檔案:

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

現在就可以用來構建dbr.node,用於Node.js的動態連結程式庫,相當於DLL。在命令列中輸入:

node-gyp configure install

這行命令幹了兩件事,首先產生了Visual Studio的工程檔案。然後調用VS的編譯器產生了動態連結程式庫。可以看下產生的檔案結構:

build    / binding.sln    / dbr.vcxproj    / dbr.vcxproj.filters    / config.gypi    / Release        / dbr.node        / dbr.pdb        / obj

更多內容可以參考官方文檔Node.js addons。

把Dynamsoft Barcode SDK封裝成Node.js擴充

接下來我們只需要使用Visual Studio來編寫代碼,構建工程就可以了。因為node-gyp在配置的時候已經把工程檔案裡的標頭檔路徑和依賴庫路徑都加進去了,我們只需要做很小的修改。現在雙擊binding.sln匯入工程。添加Dynamsoft Barcode SDK相關的標頭檔路徑和庫路徑。最後添加post-build event用於拷貝DLL到組建目錄:

copy "{installation directory}\Dynamsoft\Barcode Reader 2.0 Trial\Redist\C_C++\*.dll" "$(OutDir)"

現在開始編寫C++代碼。和Java,Python類似,在編寫native代碼的時候,需要首先註冊native函數。初始化Barcode解碼介面:

void Init(Handle<Object> exports) {    NODE_SET_METHOD(exports, "decodeFile", DecodeFile);} NODE_MODULE(dbr, Init)

接下來我們把擷取的資料轉換成v8資料類型。使用Local<Object>來儲存一個Barcode結果,使用Local<Array>來儲存所有的Local<Object>。最後通過回呼函數把結果返回到JavaScript層。

void DecodeFile(const FunctionCallbackInfo<Value>& args) {     Isolate* isolate = Isolate::GetCurrent();    HandleScope scope(isolate);     // convert v8 string to char *    String::Utf8Value utfStr(args[0]->ToString());    char *pFileName = *utfStr;     int option_iMaxBarcodesNumPerPage = -1;    int option_llBarcodeFormat = -1;     pBarcodeResultArray pResults = NULL;    ReaderOptions option;    SetOptions(&option, option_iMaxBarcodesNumPerPage, option_llBarcodeFormat);     // decode barcode image file    int ret = DBR_DecodeFile(        pFileName,        &option,        &pResults        );     if (ret == DBR_OK){        int count = pResults->iBarcodeCount;        pBarcodeResult* ppBarcodes = pResults->ppBarcodes;        pBarcodeResult tmp = NULL;         // javascript callback function        Local<Function> cb = Local<Function>::Cast(args[1]);        const unsigned argc = 1;         // array for storing barcode results        Local<Array> barcodeResults = Array::New(isolate);         for (int i = 0; i < count; i++)        {            tmp = ppBarcodes[i];             Local<Object> result = Object::New(isolate);            result->Set(String::NewFromUtf8(isolate, "format"), Number::New(isolate, tmp->llFormat));            result->Set(String::NewFromUtf8(isolate, "value"), String::NewFromUtf8(isolate, tmp->pBarcodeData));             barcodeResults->Set(Number::New(isolate, i), result);        }         // release memory        DBR_FreeBarcodeResults(&pResults);         Local<Value> argv[argc] = { barcodeResults };        cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);    }}

文檔可以參考v8.h以及Chrome V8

現在建立一個JavaScript指令檔測試一下:

var dbr = require(‘./build/Release/dbr‘);var readline = require(‘readline‘); var rl = readline.createInterface({  input: process.stdin,  output: process.stdout}); rl.question("Please input a barcode image path: ", function(answer) {  // e.g. F:\git\Dynamsoft-Barcode-Reader\Images\AllSupportedBarcodeTypes.tif  dbr.decodeFile(    answer,    function(msg){      var result = null;      for (index in msg) {        result = msg[index]        console.log(result[‘format‘]);        console.log(result[‘value‘]);        console.log("##################");      }    }  );   rl.close();});

最後通過命令列運行查看結果:

源碼

https://github.com/Dynamsoft/Dynamsoft-Barcode-Reader/tree/master/samples/Node.js

Node.js C++擴充實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.