| 5351 | |
| 5352 | template <typename T> |
| 5353 | inline void ObjectWrap<T>::FinalizeCallback(node_addon_api_basic_env env, |
| 5354 | void* data, |
| 5355 | void* /*hint*/) { |
| 5356 | // If the child class does not override _any_ Finalize() method, `env` will be |
| 5357 | // unused because of the constexpr guards. Explicitly reference it here to |
| 5358 | // bypass compiler warnings. |
| 5359 | (void)env; |
| 5360 | T* instance = static_cast<T*>(data); |
| 5361 | |
| 5362 | // Prevent ~ObjectWrap from calling napi_remove_wrap. |
| 5363 | // The instance->_ref should be deleted with napi_delete_reference in |
| 5364 | // ~Reference. |
| 5365 | instance->_finalized = true; |
| 5366 | |
| 5367 | // If class overrides the basic finalizer, execute it. |
| 5368 | if constexpr (details::HasBasicFinalizer<T>::value) { |
| 5369 | #ifndef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER |
| 5370 | HandleScope scope(env); |
| 5371 | #endif |
| 5372 | |
| 5373 | instance->Finalize(Napi::BasicEnv(env)); |
| 5374 | } |
| 5375 | |
| 5376 | // If class overrides the (extended) finalizer, either schedule it or |
| 5377 | // execute it immediately (depending on experimental features enabled). |
| 5378 | if constexpr (details::HasExtendedFinalizer<T>::value) { |
| 5379 | #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER |
| 5380 | // In experimental, attach via node_api_post_finalizer. |
| 5381 | // `PostFinalizeCallback` is responsible for deleting the `T* instance`, |
| 5382 | // after calling the user-provided finalizer. |
| 5383 | napi_status status = |
| 5384 | node_api_post_finalizer(env, PostFinalizeCallback, data, nullptr); |
| 5385 | NAPI_FATAL_IF_FAILED(status, |
| 5386 | "ObjectWrap<T>::FinalizeCallback", |
| 5387 | "node_api_post_finalizer failed"); |
| 5388 | #else |
| 5389 | // In non-experimental, this `FinalizeCallback` already executes from a |
| 5390 | // non-basic environment. Execute the override directly. |
| 5391 | // `PostFinalizeCallback` is responsible for deleting the `T* instance`, |
| 5392 | // after calling the user-provided finalizer. |
| 5393 | HandleScope scope(env); |
| 5394 | PostFinalizeCallback(env, data, static_cast<void*>(nullptr)); |
| 5395 | #endif |
| 5396 | } |
| 5397 | // If the instance does _not_ override the (extended) finalizer, delete the |
| 5398 | // `T* instance` immediately. |
| 5399 | else { |
| 5400 | delete instance; |
| 5401 | } |
| 5402 | } |
| 5403 | |
| 5404 | template <typename T> |
| 5405 | inline void ObjectWrap<T>::PostFinalizeCallback(napi_env env, |