首先
我们要先全局安装node-gyp,node-gyp具体教程移步:https://github.com/nodejs/node-gyp#installation 已安装过的可以略过
其次
进入自己的项目文件夹,例如我项目文件夹取名为c-jit-test
npm install c-jit
#然后我们的node就可以开始混写c了,直接上个相加的例子吧 语法可参考(NAN语法):https://github.com/nodejs/node-addon-examples
const CJit = require("c-jit");
const path = require("path");
let cJit = new CJit();
// run by c code sync
let funcByrunSync = cJit.runSync(`
if (info.Length() < 2) {
Nan::ThrowTypeError("Wrong number of arguments");
return;
}
if (!info[0]->IsNumber() || !info[1]->IsNumber()) {
Nan::ThrowTypeError("Wrong arguments");
return;
}
double arg0 = info[0]->NumberValue();
double arg1 = info[1]->NumberValue();
v8::Local<v8::Number> num = Nan::New(arg0 + arg1);
info.GetReturnValue().Set(num);
`);
console.log("This should be eight(by run sync):"+funcByrunSync(3,5));
运行我们的js文件,你会发现第一次它会进行编译
但是第二次运行的时候
由于c语言代码已经编译完成速度会很快(如下)
#当然混写可能难看了些(我们可以直接先写到文件中,再引用文件即可)
//run by file sync
let funcByfileSync = cJit.runByFileSync(path.join(__dirname,'test.cc'));
console.log("This should be twelve(by file sync):"+funcByfileSync(6,6));
另外以上是同步方法,还可以异步实现(异步部分,大家有兴趣可以查看)
欢迎点星和push
https://github.com/zy445566/node-c-jit#example