From dded150fa8a61bbad0f5f54900e4c7d0b87b17fd Mon Sep 17 00:00:00 2001 From: Michael Price Date: Mon, 22 Jul 2019 22:10:14 -0600 Subject: [PATCH] Allows for overriding Napi::ObjectWrap::FinalizeCallback. --- doc/object_wrap.md | 39 +++++++++++++++++++++++++++++++++++++++ napi-inl.h | 2 +- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/doc/object_wrap.md b/doc/object_wrap.md index 31be140f0..ab597adf6 100644 --- a/doc/object_wrap.md +++ b/doc/object_wrap.md @@ -544,3 +544,42 @@ name of the property. One or more of `napi_property_attributes`. Returns `Napi::PropertyDescriptor` object that represents an instance value + +### FinalizeCallback + +Allows user to be notified when externally-owned data is ready to be cleaned up +because the object with which it was associated with, has been garbage-collected. + +```cpp +static void T::FinalizeCallback(napi_env env, void* data, void* hint); +``` + +- `[in] env`: `napi_env`. +- `[in] data`: pointer to the native instance. Must be cast in method e.g. + `reinterpret_cast(data)`. +- `[in] hint`: Optional contextual hint that is passed to the finalize callback. + +`T::FinalizeCallback`is optional, defined on the derived class, must be public +and implements [napi_finalize](https://nodejs.org/api/n-api.html#n_api_napi_finalize "N-API napi_finalize documentation"). + +NOTE: Overrides default `Napi::ObjectWrap::FinalizeCallback`. The default +`Napi::ObjectWrap::FinalizeCallback` frees the native instance. A user defined +finalzier is, therefore, responsible for freeing the native instance. + +```cpp +#include +class Example : public Napi::ObjectWrap { + public: + static void FinalizeCallback(napi_env env, void* data, void* hint); + //... +}; + +void Example::FinalizeCallback(napi_env env, void* data, void* hint) +{ + Example* instance = reinterpret_cast(data); + //Do stuff... + + //Free native instance + delete instance; +} +``` \ No newline at end of file diff --git a/napi-inl.h b/napi-inl.h index 0db3c9830..3c7a32a44 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -2879,7 +2879,7 @@ inline ObjectWrap::ObjectWrap(const Napi::CallbackInfo& callbackInfo) { napi_status status; napi_ref ref; T* instance = static_cast(this); - status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref); + status = napi_wrap(env, wrapper, instance, T::FinalizeCallback, nullptr, &ref); NAPI_THROW_IF_FAILED_VOID(env, status); Reference* instanceRef = instance;