|
| 1 | +#include "napi.h" |
| 2 | + |
| 3 | +#if (NAPI_VERSION > 3) |
| 4 | + |
| 5 | +using namespace Napi; |
| 6 | + |
| 7 | +namespace { |
| 8 | + |
| 9 | +class TSFNWrap : public ObjectWrap<TSFNWrap> { |
| 10 | +public: |
| 11 | + static Object Init(Napi::Env env, Object exports); |
| 12 | + TSFNWrap(const CallbackInfo &info); |
| 13 | + |
| 14 | + Napi::Value GetContext(const CallbackInfo & /*info*/) { |
| 15 | + Reference<Napi::Value> *ctx = _tsfn.GetContext(); |
| 16 | + return ctx->Value(); |
| 17 | + }; |
| 18 | + |
| 19 | + Napi::Value Release(const CallbackInfo &info) { |
| 20 | + Napi::Env env = info.Env(); |
| 21 | + _deferred = std::unique_ptr<Promise::Deferred>(new Promise::Deferred(env)); |
| 22 | + _tsfn.Release(); |
| 23 | + return _deferred->Promise(); |
| 24 | + }; |
| 25 | + |
| 26 | +private: |
| 27 | + ThreadSafeFunction _tsfn; |
| 28 | + std::unique_ptr<Promise::Deferred> _deferred; |
| 29 | +}; |
| 30 | + |
| 31 | +Object TSFNWrap::Init(Napi::Env env, Object exports) { |
| 32 | + Function func = |
| 33 | + DefineClass(env, "TSFNWrap", |
| 34 | + {InstanceMethod("getContext", &TSFNWrap::GetContext), |
| 35 | + InstanceMethod("release", &TSFNWrap::Release)}); |
| 36 | + |
| 37 | + exports.Set("TSFNWrap", func); |
| 38 | + return exports; |
| 39 | +} |
| 40 | + |
| 41 | +TSFNWrap::TSFNWrap(const CallbackInfo &info) : ObjectWrap<TSFNWrap>(info) { |
| 42 | + Napi::Env env = info.Env(); |
| 43 | + |
| 44 | + Reference<Napi::Value> *_ctx = new Reference<Napi::Value>; |
| 45 | + *_ctx = Persistent(info[0]); |
| 46 | + |
| 47 | + _tsfn = ThreadSafeFunction::New( |
| 48 | + info.Env(), Function::New(env, [](const CallbackInfo & /*info*/) {}), |
| 49 | + Object::New(env), "Test", 1, 1, _ctx, |
| 50 | + [this](Napi::Env env, Reference<Napi::Value> *ctx) { |
| 51 | + _deferred->Resolve(env.Undefined()); |
| 52 | + ctx->Reset(); |
| 53 | + delete ctx; |
| 54 | + }); |
| 55 | +} |
| 56 | + |
| 57 | +} // namespace |
| 58 | + |
| 59 | +Object InitThreadSafeFunctionCtx(Env env) { |
| 60 | + return TSFNWrap::Init(env, Object::New(env)); |
| 61 | +} |
| 62 | + |
| 63 | +#endif |
0 commit comments