• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "myobject.h"
2 #include "../common.h"
3 
4 size_t finalize_count = 0;
5 
MyObject()6 MyObject::MyObject() : env_(nullptr), wrapper_(nullptr) {}
7 
~MyObject()8 MyObject::~MyObject() {
9   finalize_count++;
10   napi_delete_reference(env_, wrapper_);
11 }
12 
Destructor(napi_env env,void * nativeObject,void *)13 void MyObject::Destructor(
14   napi_env env, void* nativeObject, void* /*finalize_hint*/) {
15   MyObject* obj = static_cast<MyObject*>(nativeObject);
16   delete obj;
17 }
18 
19 napi_ref MyObject::constructor;
20 
Init(napi_env env)21 napi_status MyObject::Init(napi_env env) {
22   napi_status status;
23 
24   napi_value cons;
25   status = napi_define_class(
26       env, "MyObject", -1, New, nullptr, 0, nullptr, &cons);
27   if (status != napi_ok) return status;
28 
29   status = napi_create_reference(env, cons, 1, &constructor);
30   if (status != napi_ok) return status;
31 
32   return napi_ok;
33 }
34 
New(napi_env env,napi_callback_info info)35 napi_value MyObject::New(napi_env env, napi_callback_info info) {
36   size_t argc = 1;
37   napi_value args[1];
38   napi_value _this;
39   NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr));
40 
41   MyObject* obj = new MyObject();
42 
43   napi_valuetype valuetype;
44   NAPI_CALL(env, napi_typeof(env, args[0], &valuetype));
45 
46   if (valuetype == napi_undefined) {
47     obj->val_ = 0;
48   } else {
49     NAPI_CALL(env, napi_get_value_double(env, args[0], &obj->val_));
50   }
51 
52   obj->env_ = env;
53 
54   // The below call to napi_wrap() must request a reference to the wrapped
55   // object via the out-parameter, because this ensures that we test the code
56   // path that deals with a reference that is destroyed from its own finalizer.
57   NAPI_CALL(env, napi_wrap(env,
58                           _this,
59                           obj,
60                           MyObject::Destructor,
61                           nullptr,  // finalize_hint
62                           &obj->wrapper_));
63 
64   return _this;
65 }
66 
NewInstance(napi_env env,napi_value arg,napi_value * instance)67 napi_status MyObject::NewInstance(napi_env env,
68                                   napi_value arg,
69                                   napi_value* instance) {
70   napi_status status;
71 
72   const int argc = 1;
73   napi_value argv[argc] = {arg};
74 
75   napi_value cons;
76   status = napi_get_reference_value(env, constructor, &cons);
77   if (status != napi_ok) return status;
78 
79   status = napi_new_instance(env, cons, argc, argv, instance);
80   if (status != napi_ok) return status;
81 
82   return napi_ok;
83 }
84