0

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 ???
});

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks。i find this example async_work_thread_safe_function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.