Node.js invokes C/C++ extensions

2. Create a C/C++ source directory SRC 3. Write C/C++ source code hello.cc

// 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, "Hello World"));
}
 
void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}
 
NODE_MODULE(addon, init)
 
}  // namespace demo
Copy the code

4. In the hello directory of the project, create binding.gyp to compile the configuration file

{
  'targets': [
    {
      'target_name': 'hello',
      'sources': [
          'src/hello.cc'
      ],
      'conditions': [
          ['OS == "win"', 
          {
              'libraries': ['-lnode.lib']
          }
          ]
      ]
    }
  ]
}
Copy the code

5. In the hello directory of the project, write test code test.js

var addon = require('./build/Release/hello.node');
console.log(addon.hello());
Copy the code

6. Run the node-gyp command to configure the item

node-gyp configure
Copy the code

7. Run the node-gyp command to compile the project

node-gyp build
Copy the code

8. Run the test code in the hello directory of the project

node test.js
Copy the code

According to

Hello World
Copy the code

Successfully called C/C++ code with Node.js