我正在编写一个 NodeJS 插件,其中我使用了一个 C 库,可让您在某些事件中注册回调。当回调被触发时,我想调用一个 NodeJS 回调函数。问题是,在我的 C 回调函数中,当我尝试执行任何与 V8 相关的操作(例如创建 HandleScope)时,会出现分段错误。
在 test.js 中:
...
myaddon.register(function(data) {
console.log("data: " + JSON.stringify(data));
});
...
在 test.c 中:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <node.h>
#include <v8.h>
using namespace v8;
void WINAPI myEvent(int num, void * context) {
HandleScope scope; // Segmentation fault here!
Local<Function> * cb = (Local<Function>*)(context);
Local<Object> obj = Object::New();
obj->Set(String::NewSymbol("id"), Number::New(num));
const int argc = 1;
Local<Value> argv[argc] = { obj };
(*cb)->Call(Context::GetCurrent()->Global(), argc, argv);
sleep(1);
}
Handle<Value> RegisterEvent(const Arguments& args) {
HandleScope scope;
Local<Function> cb = Local<Function>::Cast(args[0]);
int callbackId = registerEvent((Event)&myEvent, &cb );
printf("callback id: %i\n", callbackId);
init();
return scope.Close(Integer::New(callbackId));
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("register"),
FunctionTemplate::New(RegisterEvent)->GetFunction());
}
NODE_MODULE(test, init)
编辑:用真实代码更新。
编辑:我刚刚更改了这个问题的标题,因为问题可能是我的回调函数无法访问 V8 上下文。因为我在创建 HandleScope 实例时遇到了分段错误,所以我看不到它可能是什么。除了这个问题,我还试图在 V8 文档中找到答案,但它很大,我没有那么多时间来测试和调查。