是否可以使用预定义的napi_threadsafe_function发送参数?

时间:2019-04-15 19:28:19

标签: c++ node.js electron node-addon-api

我有一个Electron应用程序,我使用napi构建了一个插件,并且我有一个javascript函数,可以根据字符串输入参数更新UI。

在插件中,我使用updateUI JS函数并为其创建线程安全函数回调。

然后,我开始运行一个长时间运行的函数(带有lambda),该函数最终将回调线程安全函数以更新UI。我能够成功调用该函数,但是当时看不到将参数传递给调用的方法。

我不会对已经尝试过的内容发表过多评论,但是阅读文档会使我相信这是不可能的(因为它没有提及)。在创建的4个nullptr和调用的nullptr中尝试使用“ stuff”也不成功。

但是我觉得这是一个非常简单的功能,应该可以实现,希望我误会或遗漏了一些明显的东西。

function addText(msg) {/*append stuff*/}
myModule.napiSomeFunc(addText)

//NAPI_CALL_WITH_CHECK is just a c++ macro i defined that just checks the status returned and handles it accordingly, I know it works fine.

napi_value napiSomeFunc(napi_env env, napi_callback_info cbinfo) {

        //initial callback call setup
        size_t argc = 1;
        napi_value argv[1];
        NAPI_CALL_WITH_CHECK(napi_get_cb_info, env, cbinfo, &argc, argv, nullptr, nullptr);
        napi_value cb = argv[0]; // JS function

        napi_value name;
        NAPI_CALL_WITH_CHECK(napi_create_string_utf8, env, "testname", NAPI_AUTO_LENGTH, &name);

        napi_threadsafe_function safecb;
        NAPI_CALL_WITH_CHECK(napi_create_threadsafe_function,
            env,
            cb, // The JS function to callback to
            NULL, // Optional async resource
            name, // name for ^
            0, // Maximum size of the queue. 0 for no limit.
            1, // The initial number of threads, including the main thread, which will be making use of this function
            nullptr, //optional data to pass down to function immediately below this
            nullptr, // Optional function to call when the napi_threadsafe_function is being destroyed
            nullptr, // Optional data to attach to the resulting napi_threadsafe_function
            nullptr, // (call_js_cb) Optional callback which calls the JavaScript function in response to a call on a different thread
            &safecb // Result
       );


        // Lambda runs at the end of this function
        SuperLongRunningFunction(
            "other params",
            [safecb](const Result* res) {
                string logText = "";

                if (res) {
                    logText = "yay it worked";
                } else {
                    logText = "oh no it failed";
                }

                // ** Send logText as input parameter somehow??? **

                NAPI_EXTERN napi_status stat = napi_call_threadsafe_function(
                    safecb,
                    nullptr, // data to send into JS VIA call_js_cb
                    napi_tsfn_nonblocking
                );
            }
        );

        return nullptr;
    }

在我的JavaScript代码中,我检查了该函数的空输入参数调用,并且可以看到在我的onclick中,我触发了没有输入的调用。

我需要使用logText作为输入进行呼叫,但是我不知道如何操作。

任何朝正确方向的推动将不胜感激。谢谢。

0 个答案:

没有答案