来自本机 C++ 代码的节点 js 回调抛出错误

node js callback from native C++ code is throwing errors

我正在尝试实现事件侦听器。 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()'

任何人都可以帮助我解决将 Node 函数 env 存储到 C++ 映射中的问题。我需要保存环境,以便在调用节点回调时发送响应。

Napi::Env 没有默认构造函数,因此您的 deviceNapi 结构的默认构造函数无法初始化 env 成员,因此编译器没有生成它,但您尝试在这一行调用它:

deviceNapi obj;

您可以像这样初始化它来解决这个问题:

deviceNapi obj = {env, info[1].As<Napi::Function>()};