Skip to content

Commit

Permalink
Allows for overriding Napi::ObjectWrap::FinalizeCallback.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikepricedev committed Jul 23, 2019
1 parent ac6000d commit dded150
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
39 changes: 39 additions & 0 deletions doc/object_wrap.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

This comment has been minimized.

Copy link
@gabrielschulhof

gabrielschulhof Jul 23, 2019

"Allows [the] user..."

because the object with which it was associated with, has been garbage-collected.

This comment has been minimized.

Copy link
@gabrielschulhof

gabrielschulhof Jul 23, 2019

No need for the comma after "with".


```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<T*>(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 <napi.h>
class Example : public Napi::ObjectWrap<Example> {
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<Example*>(data);
//Do stuff...
//Free native instance
delete instance;
}
```
2 changes: 1 addition & 1 deletion napi-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -2879,7 +2879,7 @@ inline ObjectWrap<T>::ObjectWrap(const Napi::CallbackInfo& callbackInfo) {
napi_status status;
napi_ref ref;
T* instance = static_cast<T*>(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<Object>* instanceRef = instance;
Expand Down

0 comments on commit dded150

Please sign in to comment.