How to call a C/C++ function from Node
A straightforward way to call C/C++ code from Node is to use node-gyp
to build a Node addon. Node kindly provides a hello world addon demo which we’ll roughly follow below.
Firstly you’ll need to install node-gyp
. When doing the initial setup, make sure you have a compatible version of Python configured. Next you’ll need to provide a binding.gyp
, this file tells node-gyp
how to build your project. A simple binding.gyp
might look like this:
{
"targets": [
{
"target_name": "binding",
"sources": [ "src/binding.cc" ]
}
]
}
A barebones binding might look like the following. While it is written in C++, you can integrate your C code in much the same way. See this article for some examples on how to mix C and C++.
#include <node.h>
#include <v8.h>
void Method(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, "hello world").ToLocalChecked());
}
void init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
NODE_SET_METHOD(exports, "foo", Method);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, init);
Following that, you can run node-gyp configure
to have node-gyp
set up build tooling, and then node-gyp build
to have it build your addon. If the output ends in gyp info ok
then you’ve just successfully built your first native addon.
You can import your binding as any old module and use it in Node:
const binding = require("./build/Release/binding");
console.log(binding.foo()); // Will log "hello world"