Ezreal
Ezreal

Reputation: 13

NAPI Addon : how to return value to javascript from c++ CALLBACK?

My project has some functionality that requires other SDK, and some of the return values of this SDK method are returned in c++ CALLBACK.

how to return value to javascript from c++ CALLBACK?

simple code like this:

c++ code

    // login callback
    void CALLBACK LoginResultCallBack(LONG lUserID)
    {
       // ??? return lUserID to javascript ???
    }

    // async login
    napi_value Login(napi_env env, napi_callback_info info) {
        // ...
        LOGIN_INFO struLoginInfo = { 0 };
        DEVICEINFO struDeviceInfoV40 = { 0 };
        // set login callback
        struLoginInfo.cbLoginResult = LoginResultCallBack;
        SDK_Login(&struLoginInfo, &struDeviceInfoV40);

        return 0;
    }

    napi_value Init(napi_env env, napi_value exports) {
        napi_property_descriptor des= { "login", NULL, Login, NULL, NULL, NULL, napi_default, NULL };
        assert(napi_define_properties(env, exports, 1, &des) == napi_ok);
        return exports;
    }

    NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)


js code

sdk.login((userId) => {
  // ??? get userId from c++ CALLBACK ???
});

Upvotes: 0

Views: 1922

Answers (1)

bmacnaughton
bmacnaughton

Reputation: 5308

i think this is the answer you're looking for:

napi_value RunCallback(napi_env env, const napi_callback_info info) {
    napi_status status;

    size_t argc = 1;
    napi_value args[1];
    status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    assert(status == napi_ok);

    napi_value cb = args[0];

    napi_value argv[1];
    status = napi_create_string_utf8(env, "hello world", NAPI_AUTO_LENGTH, argv);
    assert(status == napi_ok);

    napi_value global;
    status = napi_get_global(env, &global);
    assert(status == napi_ok);

    napi_value result;
    status = napi_call_function(env, global, cb, 1, argv, &result);
    assert(status == napi_ok);

    return nullptr;
}

it's directly from node-addon-examples and there are probably other helpful examples too.

Upvotes: 1

Related Questions