napi_add_finalizer


napi_status napi_add_finalizer(napi_env env,
                               napi_value js_object,
                               void* native_object,
                               napi_finalize finalize_cb,
                               void* finalize_hint,
                               napi_ref* result); 
  • [in] env:调用该 API 所处的环境。
  • [in] js_object:将要附加原生数据的 JavaScript 对象。
  • [in] native_object:将附加到 JavaScript 对象的原生数据。
  • [in] finalize_cb:在 JavaScript 对象准备被垃圾回收时,用于释放原生数据的原生回调。napi_finalize 提供了更多细节。
  • [in] finalize_hint:可选的上下文提示,会传递给 finalize 回调。
  • [out] result:可选的 JavaScript 对象引用。

如果 API 成功,则返回 napi_ok

【Returns napi_ok if the API succeeded.】

添加一个 napi_finalize 回调,当 js_object 中的 JavaScript 对象准备好进行垃圾回收时将被调用。这个 API 类似于 napi_wrap(),但是:

【Adds a napi_finalize callback which will be called when the JavaScript object in js_object is ready for garbage collection. This API is similar to napi_wrap() except that:】

  • 使用 napi_unwrap() 无法在以后检索本地数据,
  • 也无法在以后使用 napi_remove_wrap() 删除,
  • 该 API 可以多次调用以不同的数据项将它们附加到 JavaScript 对象上,
  • 通过该 API 操作的对象可以与 napi_wrap() 一起使用。

⚠️注意:可选返回的引用(如果获得)应仅在 finalize 回调调用时通过 napi_delete_reference 删除。如果在此之前删除,可能永远不会调用 finalize 回调。因此,在获取引用时,还需要一个 finalize 回调,以确保引用能够正确释放。

Caution: The optional returned reference (if obtained) should be deleted via napi_delete_reference ONLY in response to the finalize callback invocation. If it is deleted before then, then the finalize callback may never be invoked. Therefore, when obtaining a reference a finalize callback is also required in order to enable correct disposal of the reference.】