Nodejs 调用 C++(addon的学习)

先来看一段略有脑洞的js代码:

1
2
3
4
5
6
7
8
var geek = require('GeekIt');
console.log(geek);
console.log(geek());
console.log(geek()());
console.log(geek()()());
console.log(geek()()()());
console.log(geek()()()()());
console.log(geek()()()()()());

然后这段代码的输出:

这个helloworld真实羞涩呀,藏了6层。来看看这个具体是怎么实现的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <node.h>

using namespace v8;

void MyFunction5(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}

void MyFunction4(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction5);
Local<Function> fn = tpl->GetFunction();
fn->SetName(String::NewFromUtf8(isolate, "MyFunction5"));
args.GetReturnValue().Set(fn);
}

void MyFunction3(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction4);
Local<Function> fn = tpl->GetFunction();
fn->SetName(String::NewFromUtf8(isolate, "MyFunction4"));
args.GetReturnValue().Set(fn);
}

void MyFunction2(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction3);
Local<Function> fn = tpl->GetFunction();
fn->SetName(String::NewFromUtf8(isolate, "MyFunction3"));
args.GetReturnValue().Set(fn);
}

void MyFunction1(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction2);
Local<Function> fn = tpl->GetFunction();
fn->SetName(String::NewFromUtf8(isolate, "MyFunction2"));
args.GetReturnValue().Set(fn);
}

void CreateFunction(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction1);
Local<Function> fn = tpl->GetFunction();
fn->SetName(String::NewFromUtf8(isolate, "MyFunction1"));
args.GetReturnValue().Set(fn);
}

void Init(Handle<Object> exports, Handle<Object> module) {
NODE_SET_METHOD(module, "exports", CreateFunction);
}

NODE_MODULE(GeekIt, Init)

首先模块初始化的时候把CreateFunction这个函数体作为exports对象的参数。所以在js代码中,执行geek()相当于执行了CreateFunction这个函数。在这个函数中,以MyFunction1作为返回值,所以紧接着geek()再加一对括号相当于执行了MyFunction1。以此类推,直到最后输出helloworld。