我正在尝试从我的函数的另一个点调用V8中的回调。因此,这段代码注册了回调:
if (args.Length())
{
String::Utf8Value event(args[0]->ToString());
if (event.length())
{
Isolate* isolate = V8Interface::getCurrent()->getIsolate();
Locker locker(isolate);
HandleScope scope(isolate);
callback cb = callback(isolate, Local<Function>::Cast(args[1]));
if(!events.count(*event))
{
events[*event] = callbacks({ cb });
}
else
{
events.find(*event)->second.push_back(cb);
}
}
}
而这个调用它:
void trigger(std::string event)
{
Isolate* isolate = V8Interface::getCurrent()->getIsolate();
Locker locker(isolate);
HandleScope scope(isolate);
if(events.count(event))
{
for(callback cb : events.find(event)->second)
{
Local<Function> local = Local<Function>::New(isolate, cb);
local->Call(isolate->GetCurrentContext()->Global(), 0, {});
}
}
}
触发函数可以在我的C++代码的任何位置随时调用。我尝试了一个简单的例子(初始化v8然后调用触发器),结果如下:
#
# Fatal error in C:\OgreSDK\Projects\whitedrop\third_party\io.js\deps\v8\src/api.h, line 386
# CHECK(allow_empty_handle || that != 0) failed
#
这是我的主函数:
Scribe::V8Interface v8Interface = Scribe::V8Interface();
v8Interface.initialize();
for(Whitedrop::WorldEvent* event : Whitedrop::worldEvents)
{
event->onStart();
}
您可以在此处获取整个源代码:
https://github.com/whitedrop/whitedrop/tree/feature/v8
第386行是:
/**
* Create a local handle for the content of another handle.
* The referee is kept alive by the local handle even when
* the original handle is destroyed/disposed.
*/
V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that); // <<<<<<
V8_INLINE static Local<T> New(Isolate* isolate,
const PersistentBase<T>& that);
编辑:我尝试了Ben Noordhuis的方法,如下:
Isolate* isolate = V8Interface::getCurrent()->getIsolate();
Locker locker(isolate);
HandleScope scope(isolate);
callback cb;
cb.Reset(isolate, Local<Function>::Cast(args[1]));
并且要调用:
Isolate* isolate = V8Interface::getCurrent()->getIsolate();
Locker locker(isolate);
HandleScope scope(isolate);
if(events.count(event))
{
for(callback cb : events.find(event)->second)
{
Local<Function> local = Local<Function>::New(isolate, cb);
local->Call(isolate->GetCurrentContext()->Global(), 0, {});
}
}
但是仍然出现错误 :'(