• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <stdlib.h>
2 #include <js_native_api.h>
3 #include "../common.h"
4 
5 static size_t g_call_count = 0;
6 
Destructor(napi_env env,void * data,void * nothing)7 static void Destructor(napi_env env, void* data, void* nothing) {
8   napi_ref* ref = data;
9   NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, *ref));
10   free(ref);
11 }
12 
NoDeleteDestructor(napi_env env,void * data,void * hint)13 static void NoDeleteDestructor(napi_env env, void* data, void* hint) {
14   napi_ref* ref = data;
15   size_t* call_count = hint;
16 
17   // This destructor must be called exactly once.
18   if ((*call_count) > 0) abort();
19   *call_count = ((*call_count) + 1);
20   free(ref);
21 }
22 
New(napi_env env,napi_callback_info info)23 static napi_value New(napi_env env, napi_callback_info info) {
24   size_t argc = 1;
25   napi_value js_this, js_delete;
26   bool delete;
27   napi_ref* ref = malloc(sizeof(*ref));
28 
29   NAPI_CALL(env,
30       napi_get_cb_info(env, info, &argc, &js_delete, &js_this, NULL));
31   NAPI_CALL(env, napi_get_value_bool(env, js_delete, &delete));
32 
33   if (delete) {
34     NAPI_CALL(env,
35         napi_wrap(env, js_this, ref, Destructor, NULL, ref));
36   } else {
37     NAPI_CALL(env,
38         napi_wrap(env, js_this, ref, NoDeleteDestructor, &g_call_count, ref));
39   }
40   NAPI_CALL(env, napi_reference_ref(env, *ref, NULL));
41 
42   return js_this;
43 }
44 
45 EXTERN_C_START
Init(napi_env env,napi_value exports)46 napi_value Init(napi_env env, napi_value exports) {
47   napi_value myobj_ctor;
48   NAPI_CALL(env,
49       napi_define_class(
50           env, "MyObject", NAPI_AUTO_LENGTH, New, NULL, 0, NULL, &myobj_ctor));
51   NAPI_CALL(env,
52       napi_set_named_property(env, exports, "MyObject", myobj_ctor));
53   return exports;
54 }
55 EXTERN_C_END
56