对象生命周期管理
¥Object lifetime management
在进行 Node-API 调用时,底层 VM 的堆中对象的句柄可能会作为 napi_values
返回。这些句柄必须持有对象 'live',直到原生代码不再需要它们,否则这些对象可能会在原生代码使用完它们之前被收集。
¥As Node-API calls are made, handles to objects in the heap for the underlying
VM may be returned as napi_values
. These handles must hold the
objects 'live' until they are no longer required by the native code,
otherwise the objects could be collected before the native code was
finished using them.
当对象句柄返回时,它们与 'scope' 相关联。默认作用域的生命周期与本地方法调用的生命周期相关。结果是,默认情况下,句柄保持有效,并且与这些句柄关联的对象将在原生方法调用的生命周期内保持活动状态。
¥As object handles are returned they are associated with a 'scope'. The lifespan for the default scope is tied to the lifespan of the native method call. The result is that, by default, handles remain valid and the objects associated with these handles will be held live for the lifespan of the native method call.
然而,在许多情况下,句柄必须在比本地方法更短或更长的生命周期内保持有效。以下部分描述了可用于更改默认句柄寿命的 Node-API 函数。
¥In many cases, however, it is necessary that the handles remain valid for either a shorter or longer lifespan than that of the native method. The sections which follow describe the Node-API functions that can be used to change the handle lifespan from the default.