napi_threadsafe_function_call_js


与异步线程安全函数调用一起使用的函数指针。回调将在主线程上调用。它的目的是使用从一个辅助线程通过队列到达的数据项来构造调用 JavaScript 所需的参数,通常是通过 napi_call_function,然后调用 JavaScript。

¥Function pointer used with asynchronous thread-safe function calls. The callback will be called on the main thread. Its purpose is to use a data item arriving via the queue from one of the secondary threads to construct the parameters necessary for a call into JavaScript, usually via napi_call_function, and then make the call into JavaScript.

通过队列从辅助线程到达的数据在 data 参数中给出,要调用的 JavaScript 函数在 js_callback 参数中给出。

¥The data arriving from the secondary thread via the queue is given in the data parameter and the JavaScript function to call is given in the js_callback parameter.

Node-API 在调用此回调之前设置环境,因此通过 napi_call_function 而不是通过 napi_make_callback 调用 JavaScript 函数就足够了。

¥Node-API sets up the environment prior to calling this callback, so it is sufficient to call the JavaScript function via napi_call_function rather than via napi_make_callback.

回调函数必须满足以下签名:

¥Callback functions must satisfy the following signature:

typedef void (*napi_threadsafe_function_call_js)(napi_env env,
                                                 napi_value js_callback,
                                                 void* context,
                                                 void* data); 
  • [in] env:用于 API 调用的环境,或者 NULL,如果线程安全函数正在被拆除并且 data 可能需要被释放。

    ¥[in] env: The environment to use for API calls, or NULL if the thread-safe function is being torn down and data may need to be freed.

  • [in] js_callback:要调用的 JavaScript 函数,或者 NULL,如果线程安全函数正在被拆除并且 data 可能需要被释放。如果线程安全函数是在没有 js_callback 的情况下创建的,它也可能是 NULL

    ¥[in] js_callback: The JavaScript function to call, or NULL if the thread-safe function is being torn down and data may need to be freed. It may also be NULL if the thread-safe function was created without js_callback.

  • [in] context:用于创建线程安全函数的可选数据。

    ¥[in] context: The optional data with which the thread-safe function was created.

  • [in] data:由辅助线程创建的数据。回调负责将此原生数据转换为 JavaScript 值(使用 Node-API 函数),这些值可以在调用 js_callback 时作为参数传递。这个指针完全由线程和这个回调管理。因此这个回调应该释放数据。

    ¥[in] data: Data created by the secondary thread. It is the responsibility of the callback to convert this native data to JavaScript values (with Node-API functions) that can be passed as parameters when js_callback is invoked. This pointer is managed entirely by the threads and this callback. Thus this callback should free the data.

除非出于 对象生命周期管理 中讨论的原因,否则无需在函数体内创建句柄和/或回调范围。

¥Unless for reasons discussed in Object Lifetime Management, creating a handle and/or callback scope inside the function body is not necessary.