对象生命周期管理


【Object lifetime management】

在进行 Node-API 调用时,可能会返回指向底层虚拟机堆中对象的句柄,称为 napi_values。这些句柄必须保持对象“活动”,直到原生代码不再需要它们,否则在原生代码使用完之前,这些对象可能会被回收。

【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.】

当返回对象句柄时,它们会与“作用域”关联。默认作用域的生命周期与本地方法调用的生命周期绑定。其结果是,默认情况下,句柄保持有效,并且与这些句柄关联的对象将在本地方法调用的生命周期内保持存活。

【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.】