napi_create_external_buffer
napi_status napi_create_external_buffer(napi_env env,
size_t length,
void* data,
napi_finalize finalize_cb,
void* finalize_hint,
napi_value* result) [in] env:调用该 API 时所处的环境。[in] length:输入缓冲区的字节大小(应与新缓冲区的大小相同)。[in] data:指向要暴露给 JavaScript 的底层缓冲区的原始指针。[in] finalize_cb:可选回调,当ArrayBuffer被回收时调用。napi_finalize提供了更多细节。[in] finalize_hint:在收集期间传递给 finalize 回调的可选提示。[out] result:一个表示node::Buffer的napi_value。
如果 API 成功,则返回 napi_ok。
【Returns napi_ok if the API succeeded.】
除 Node.js 外的一些运行时已停止支持外部缓冲区。
在除 Node.js 外的运行时中,该方法可能返回 napi_no_external_buffers_allowed,以表示不支持外部缓冲区。Electron 就是其中一种运行时,如本问题中所述 electron/issues/35801。
为了保持与所有运行时的最广泛兼容性,你可以在包含 node-api 头文件之前在你的插件中定义 NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED。这样做会隐藏创建外部缓冲区的两个函数。这将确保如果你不小心使用了其中一个方法,会发生编译错误。
【In order to maintain broadest compatibility with all runtimes
you may define NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED in your addon before
includes for the node-api headers. Doing so will hide the 2 functions
that create external buffers. This will ensure a compilation error
occurs if you accidentally use one of these methods.】
这个 API 会分配一个 node::Buffer 对象,并用传入缓冲区支持的数据初始化它。虽然这仍然是一个完全支持的数据结构,但在大多数情况下使用 TypedArray 就足够了。
【This API allocates a node::Buffer object and initializes it with data
backed by the passed in buffer. While this is still a fully-supported data
structure, in most cases using a TypedArray will suffice.】
该 API 添加了一个 napi_finalize 回调,当刚创建的 JavaScript 对象被垃圾回收时,该回调将被调用。
【The API adds a napi_finalize callback which will be called when the JavaScript
object just created has been garbage collected.】
对于 Node.js >=4,Buffer 是 Uint8Array。
【For Node.js >=4 Buffers are Uint8Arrays.】