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] env
: The environment that the API is invoked under. -
[in] length
:输入缓冲区的大小(以字节为单位)(应与新缓冲区的大小相同)。¥
[in] length
: Size in bytes of the input buffer (should be the same as the size of the new buffer). -
[in] data
:指向底层缓冲区的原始指针以暴露给 JavaScript。¥
[in] data
: Raw pointer to the underlying buffer to expose to JavaScript. -
[in] finalize_cb
:收集ArrayBuffer
时调用的可选回调。napi_finalize
提供了更多详细信息。¥
[in] finalize_cb
: Optional callback to call when theArrayBuffer
is being collected.napi_finalize
provides more details. -
[in] finalize_hint
:在收集期间传递给最终回调的可选提示。¥
[in] finalize_hint
: Optional hint to pass to the finalize callback during collection. -
[out] result
:一个napi_value
代表一个node::Buffer
。¥
[out] result
: Anapi_value
representing anode::Buffer
.
如果 API 成功,则返回 napi_ok
。
¥Returns napi_ok
if the API succeeded.
Node.js 以外的一些运行时已放弃对外部缓冲区的支持。在 Node.js 以外的运行时,此方法可能会返回 napi_no_external_buffers_allowed
以指示不支持外部缓冲区。如本期 electron/issues/35801 中所述,Electron 就是这样一种运行时。
¥Some runtimes other than Node.js have dropped support for external buffers.
On runtimes other than Node.js this method may return
napi_no_external_buffers_allowed
to indicate that external
buffers are not supported. One such runtime is Electron as
described in this issue
electron/issues/35801.
为了保持与所有运行时的最广泛兼容性,你可以在包含节点 API 标头之前在你的插件中定义 NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
。这样做将隐藏创建外部缓冲区的 2 个函数。如果你不小心使用其中一种方法,这将确保发生编译错误。
¥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 Buffers
是 Uint8Array
。
¥For Node.js >=4 Buffers
are Uint8Array
s.