Nodejs 使用 addons 调用c++ 初体验

纠结很久,决定写一点遇到的“坑”。

基础环境:win7-64bit  node(v7.5.0)   这些安装实在是太方便了,自行准备吧。

1. 安装 python(2.7.x ),用npm安装 node-gyp(3.5.0),创建一个文件夹来存放 binding.gyp hello.cc test.js

 binding.gyp 内容如下:

1 {
2   "targets": [
3     {
4       "target_name": "hello",
5       "sources": [ "hello.cc" ]
6     }
7   ]
8 }
View Code

hello.cc  内容如下:

 1 #include <v8.h>
 2 #include <node.h>
 3 
 4 using namespace node;
 5 using namespace v8;
 6 
 7 void Method(const v8::FunctionCallbackInfo<v8::Value>& args) {
 8 v8::Isolate* isolate = args.GetIsolate();
 9 v8::HandleScope scope(isolate);
10 args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, "Hello world"));
11 }
12 
13 void init(v8::Local<v8::Object> target) {
14 NODE_SET_METHOD(target, "hello", Method);
15 }
16 
17 NODE_MODULE(binding, init);
View Code

test.js 内容如下:

var addon = require('./build/Release/hello');
console.log(addon.hello());  
View Code

2. 直接执行 node-gyp configure build 

3.尝试运行一下吧

补充:

node-gyp configure 如果失败就多尝试几次,毕竟有些站点链接太慢

node-gyp build 失败的话,对比一下 hello.cc (格外注意,hello.cc 以后可能编译不通过,随时关注一下 v8 ,及时修改一下)

原文地址:https://www.cnblogs.com/bhfdz/p/6490875.html