我正在爲C++庫構建一個節點模塊包裝器,以通過Nan將日誌信息傳遞給JavaScript。爲此,NAN_Method可用於註冊回調。回調處理程序必須通過vlAddLogListener()
將自身註冊爲C++庫中的回調。 LoggingCallbackHandler
從庫函數dispatchEvent
(一個C++函數)接收消息。如果我收到日誌,我想調用JavaScript回調來傳遞數據。node.js Nan:在C++函數中調用JavaScript回調
函數dispatchEvent
未在Nan上下文中調用,因此我沒有範圍/上下文並且沒有對v8的訪問權限。如何調用JavaScript回調?
的代碼看起來是這樣的:
NAN_METHOD(registerLoggingCallback)
{
v8::Isolate* isolate = info.GetIsolate();
v8::Local<v8::Function> fun = info[0].As<v8::Function>();
lch = new LoggingCallbackHandler(isolate, fun);
}
LoggingCallbackHandler::LoggingCallbackHandler(v8::Isolate* isolate, v8::Local<v8::Function> fun) :
_cb(isolate, fun)
{
vlAddLogListener(&LoggingCallbackHandler::dispatchEvent, this);
}
void VL_CALLINGCONVENTION LoggingCallbackHandler::dispatchEvent(const char* eventData, void* clientData)
{
// here I want to process the data and call the JavaScript callback
v8::Local<v8::Function> f = v8::Local<v8::Function>::New(Nan::GetCurrentContext()->Global()->GetIsolate(), _cb);
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), f, argc, argv);
}