1#include "myobject.h" 2#include "../common.h" 3 4size_t finalize_count = 0; 5 6MyObject::MyObject() : env_(nullptr), wrapper_(nullptr) {} 7 8MyObject::~MyObject() { 9 finalize_count++; 10 napi_delete_reference(env_, wrapper_); 11} 12 13void MyObject::Destructor( 14 napi_env env, void* nativeObject, void* /*finalize_hint*/) { 15 MyObject* obj = static_cast<MyObject*>(nativeObject); 16 delete obj; 17} 18 19napi_ref MyObject::constructor; 20 21napi_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 35napi_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 NODE_API_CALL(env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr)); 40 41 MyObject* obj = new MyObject(); 42 43 napi_valuetype valuetype; 44 NODE_API_CALL(env, napi_typeof(env, args[0], &valuetype)); 45 46 if (valuetype == napi_undefined) { 47 obj->val_ = 0; 48 } else { 49 NODE_API_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 NODE_API_CALL(env, 58 napi_wrap(env, _this, obj, MyObject::Destructor, 59 nullptr /* finalize_hint */, &obj->wrapper_)); 60 61 return _this; 62} 63 64napi_status MyObject::NewInstance(napi_env env, 65 napi_value arg, 66 napi_value* instance) { 67 napi_status status; 68 69 const int argc = 1; 70 napi_value argv[argc] = {arg}; 71 72 napi_value cons; 73 status = napi_get_reference_value(env, constructor, &cons); 74 if (status != napi_ok) return status; 75 76 status = napi_new_instance(env, cons, argc, argv, instance); 77 if (status != napi_ok) return status; 78 79 return napi_ok; 80} 81