node. js C + + extension implementation

Source: Internet
Author: User

Because of the node.js,javascript can be used for server-side programming. With various extensions, node. js can become very powerful. Share today how to create a node. js extension in C + +.

Reference Original: Making dynamsoft Barcode SDK an Addon for node. js

Build NODEJS development environment

To build the extension, you need to install Node-gyp:

NPM install-g Node-gyp

This library contains the header files and dependent libraries required by the JavaScript V8 engine.

Create a C + + file dbr.cc and configuration file Binding.gyp. Open the configuration file and include the extension and source code files:

{"Targets": [{"Target_name": "DBR", "Sources": ["dbr.cc"]}]}

can now be used to build Dbr.node, the dynamic link library for node. js, equivalent to a DLL. On the command line, enter:

Node-gyp Configure Install

This line of command did two things, first generating a project file for Visual Studio. Then the compiler that calls vs builds the dynamic-link library. You can look at the resulting file structure:

Build/binding.sln/dbr.vcxproj/dbr.vcxproj.filters/config.gypi/release/dbr.node/ Dbr.pdb/obj

For more information, refer to the official document, node. js Addons.

Encapsulating the Dynamsoft Barcode SDK as a node. js extension

Next we just need to use Visual Studio to write code and build the project. Because Node-gyp has added the header file path and the dependent library path to the project file at the time of configuration, we only need to make minor changes. Now double-click the binding.sln Import Project. Add Dynamsoft Barcode SDK-related header file path and library path. Finally add the post-build event to copy the DLL to the build directory:

Copy "{Installation Directory}\dynamsoft\barcode Reader 2.0 Trial\redist\c_c++\*.dll" "$ (OutDir)"

Now start writing C + + code. Similar to Java,python, when writing native code, you need to register the native function first. Initialize the barcode decoding interface:

void Init (Handle<object> exports) {Node_set_method (exports, "DecodeFile", DecodeFile);} Node_module (DBR, Init)

The

Next we convert the obtained data into the V8 data type. Use local<object> to store a barcode result, using local<array> to store all local<object> . Finally, the result is returned to the JavaScript layer through a callback function.

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&NBSP;==&NBSP;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));        &nbsP;     barcoderesults->set (Number::new (isolate, i),  result);         }         // release  memory        dbr_freebarcoderesults (&pResults);          local<value> argv[argc] = { barcoderesults  };        cb->call (Isolate->getcurrentcontext ()->Global (),  argc, argv);     }}

Documents can refer to V8.h and chrome V8

Now create a JavaScript script file to test it:

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 ();});

Finally, run through the command line to view the results:

Source

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

node. js C + + extension implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.