无法通过“回调"访问V8上下文功能 [英] Can't access V8 Context in "callback" function
问题描述
我正在编写一个NodeJS插件,其中使用了一个C库,该库可让您在某些事件下注册回调.触发回调后,我想调用NodeJS回调函数.问题是,在我的C回调函数中,尝试执行与V8相关的任何操作(例如创建HandleScope)时都会遇到分段错误.
I am writing a NodeJS addon where I use a C library that lets you register a callback at certain events. When the callback is fired I want to call a NodeJS callback function. The problem is that in my C callback function I get a segmentation fault when trying to do anything V8 related, like creating a 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文档中找到答案,但这非常庞大,而且我没有太多时间来测试和研究.
I just changed the title of this issue since the problem is probably that my callback function can't access the V8 Context. Since I get a segmentation fault when creating HandleScope instance I can't see what else it might be. In addition to this question I AM trying to find the answer in the V8 documentation, but it is huge and I don't have that much time to test and investigate.
推荐答案
必须在V8线程中调用处理程序函数myEvent()
.如果没有,则必须将事件通知发布到V8线程中:
Your handler function myEvent()
must be called in V8 thread. If not, you have to post the event notification into the V8 thread:
https://stackoverflow.com/a/15701160/1355844
https://stackoverflow.com/a/22946062/1355844
这篇关于无法通过“回调"访问V8上下文功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!