我正在尝试实现事件侦听器。Node js 将订阅事件(使用 C++ 函数)。当事件发生时,C++ 应该通知节点 js。
JS代码:
pal.subscribeEvent("ONSTATECHANGE", function(a) { console.log("Event received for ONSTATECHAN";});
function kcb (a) {
console.log("KCB .....ONSTATECHAN"+JSON.stringify(a));
}
pal.subscribeEvent("ONSTATECHANGE", kcb);
C++ 代码:
struct deviceNapi {
Napi::Env env; // to store JS Function Env
Napi::Function jsCallback; // to Store JS function
};
//std::multimap<int, Napi::Function> deviceEventMgmt;
std::multimap<int, struct deviceNapi> deviceEventMgmt;
Napi::Value PAL::subscribeEvent(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
int eventID = info[0].As<Napi::Number>().Int32Value();
deviceNapi obj;
obj.env = env;
obj.jsCallback = info[1].As<Napi::Function>();
deviceEventMgmt.insert(std::make_pair(eventID, obj));
/*Napi::Function jsCallback = info[1].As<Napi::Function>();
deviceEventMgmt.insert(std::make_pair(eventID, jsCallback));*/
}
void ProcessDeviceEvent(int evt, DeviceEvtData data) {
switch(evt) {
case ONSTATECHANGE:
for(auto it = deviceEventMgmt.begin(); it != deviceEventMgmt.end(); it ++) {
if(it->first == ENUM_VERIZON_DEVICE_PENDING_RESET) {
Napi::Env env = it.second.env;
Napi::Object ret = Napi::Object::New(env);
ret.Set("reason", Napi::String::New(env, data.resetReason));
ret.Set("time", Napi::Number::New(env, data.seconds));
it->second.jsCallback.Call(ret);
}
}
/*for(auto it = deviceEventMgmt.begin(); it != deviceEventMgmt.end(); it ++) {
if(it->first == ENUM_VERIZON_DEVICE_PENDING_RESET) {
it->second.Call();
}
}*/
break;
default:
std::cout << "ProcessDeviceEvent : Currently not handling evt : " << evt << std::endl;
break;
}
}
C++ 代码在编译时抛出错误
../PAL.cpp: In member function 'Napi::Value PAL:: subscribeEvent(const Napi::CallbackInfo&)':
../PAL.cpp:1915:13: error: use of deleted function 'deviceNapi::deviceNapi()'
deviceNapi obj;
^~~
../PAL.cpp:1903:8: note: 'deviceNapi::deviceNapi()' is implicitly deleted because the default definition would be ill-formed:
struct deviceNapi {
^~~~~~~~~~
../PAL.cpp:1903:8: error: no matching function for call to 'Napi::Env::Env()'
任何人都可以帮我解决如何解决将节点函数 env 存储到 C++ 映射中的问题。我需要保存环境,以便在调用节点回调时发送响应。