From 39267baf1ba985275f74991fef6faac2ccf8e495 Mon Sep 17 00:00:00 2001 From: Julian Mesa Date: Wed, 23 Nov 2022 18:41:43 +0100 Subject: [PATCH] src: make CleanupHook public PR-URL: https://github.com/nodejs/node-addon-api/pull/1240 Reviewed-By: Michael Dawson <midawson@redhat.com Reviewed-By: Chengzhong Wu <legendecas@gmail.com> Also fixed a bad #endif position --- napi-inl.h | 5 +++++ napi.h | 14 ++++++-------- test/env_cleanup.cc | 12 ++++++++++++ 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/napi-inl.h b/napi-inl.h index 631045715..90ce3a2da 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -6242,6 +6242,11 @@ Env::CleanupHook Env::AddCleanupHook(Hook hook) { return CleanupHook(*this, hook); } +template +Env::CleanupHook::CleanupHook() { + data = nullptr; +} + template Env::CleanupHook::CleanupHook(Napi::Env env, Hook hook) : wrapper(Env::CleanupHook::Wrapper) { diff --git a/napi.h b/napi.h index 91208b107..3fa4df653 100644 --- a/napi.h +++ b/napi.h @@ -283,10 +283,7 @@ using MaybeOrValue = T; /// corresponds to an Isolate. class Env { private: -#if NAPI_VERSION > 2 - template - class CleanupHook; -#endif // NAPI_VERSION > 2 + napi_env _env; #if NAPI_VERSION > 5 template static void DefaultFini(Env, T* data); @@ -310,6 +307,9 @@ class Env { MaybeOrValue RunScript(String script) const; #if NAPI_VERSION > 2 + template + class CleanupHook; + template CleanupHook AddCleanupHook(Hook hook); @@ -335,13 +335,11 @@ class Env { void SetInstanceData(DataType* data, HintType* hint) const; #endif // NAPI_VERSION > 5 - private: - napi_env _env; - #if NAPI_VERSION > 2 template class CleanupHook { public: + CleanupHook(); CleanupHook(Env env, Hook hook, Arg* arg); CleanupHook(Env env, Hook hook); bool Remove(Env env); @@ -357,8 +355,8 @@ class Env { Arg* arg; } * data; }; -}; #endif // NAPI_VERSION > 2 +}; /// A JavaScript value of unknown type. /// diff --git a/test/env_cleanup.cc b/test/env_cleanup.cc index 44be0d5f7..a0ef62b2c 100644 --- a/test/env_cleanup.cc +++ b/test/env_cleanup.cc @@ -20,6 +20,13 @@ static void cleanupVoid() { static int secret1 = 42; static int secret2 = 43; +class TestClass { + public: + Env::CleanupHook hook; + + void removeHook(Env env) { hook.Remove(env); } +}; + Value AddHooks(const CallbackInfo& info) { auto env = info.Env(); @@ -72,6 +79,11 @@ Value AddHooks(const CallbackInfo& info) { added += !hook5.IsEmpty(); added += !hook6.IsEmpty(); + // Test store a hook in a member class variable + auto myclass = TestClass(); + myclass.hook = env.AddCleanupHook(cleanup, &secret1); + myclass.removeHook(env); + return Number::New(env, added); }