diff --git a/napi-inl.h b/napi-inl.h index c07b4ca22..9ca0a487f 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -345,6 +345,11 @@ inline T* Env::GetInstanceData() { template void Env::DefaultFini(Env, T* data) { delete data; } + +template +void Env::DefaultFiniWithHint(Env, DataType* data, HintType*) { + delete data; +} #endif // NAPI_VERSION > 5 //////////////////////////////////////////////////////////////////////////////// diff --git a/napi.h b/napi.h index 59a02f51c..926a65fd4 100644 --- a/napi.h +++ b/napi.h @@ -200,6 +200,14 @@ namespace Napi { template using Finalizer = void (*)(Env, T*); template fini = Env::DefaultFini> void SetInstanceData(T* data); + + template + using FinalizerWithHint = void (*)(Env, DataType*, HintType*); + template fini = + Env::DefaultFiniWithHint> + void SetInstanceData(DataType* data, HintType* hint); #endif // NAPI_VERSION > 5 private: diff --git a/test/addon_data.cc b/test/addon_data.cc index 021f23f90..45652bed6 100644 --- a/test/addon_data.cc +++ b/test/addon_data.cc @@ -49,15 +49,22 @@ class Addon { info.Env().GetInstanceData()->verbose = info[0].As(); } - Addon(Napi::Env env): VerboseIndicator(VerboseIndicator::Init(env)) {} + Addon(Napi::Env env, uint32_t hint = 0) : + hint(hint), VerboseIndicator(VerboseIndicator::Init(env)) {} ~Addon() { if (verbose) { fprintf(stderr, "addon_data: Addon::~Addon\n"); + if (hint > 0) { + fprintf(stderr, "hint: %u\n", hint); + } } } - static Napi::Object Init(Napi::Env env) { - env.SetInstanceData(new Addon(env)); + static Napi::Object Init(Napi::Env env, Napi::Value hint) { + if (!hint.IsNumber()) { + NAPI_THROW(Napi::Error::New(env, "Expected number"), Napi::Object()); + } + env.SetInstanceData(new Addon(env, hint.As())); Napi::Object result = Napi::Object::New(env); result.DefineProperties({ Napi::PropertyDescriptor::Accessor("verbose"), @@ -68,10 +75,17 @@ class Addon { private: bool verbose = false; + uint32_t hint = 0; Napi::FunctionReference VerboseIndicator; }; +// We use an addon factory so we can cover both the case where there is an +// instance data hint and the case where there isn't. +static Napi::Value AddonFactory(const Napi::CallbackInfo& info) { + return Addon::Init(info.Env(), info[0]); +} + Napi::Object InitAddonData(Napi::Env env) { - return Addon::Init(env); + return Napi::Function::New(env, AddonFactory); } #endif // (NAPI_VERSION > 5)