1 #include <stdlib.h>
2 #include <node_api.h>
3 #include "../../js-native-api/common.h"
4
MyObject_fini(napi_env env,void * data,void * hint)5 static void MyObject_fini(napi_env env, void* data, void* hint) {
6 napi_ref* ref = data;
7 napi_value global;
8 napi_value cleanup;
9 NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &global));
10 NAPI_CALL_RETURN_VOID(
11 env, napi_get_named_property(env, global, "cleanup", &cleanup));
12 napi_status status = napi_call_function(env, global, cleanup, 0, NULL, NULL);
13 // We may not be allowed to call into JS, in which case a pending exception
14 // will be returned.
15 NAPI_ASSERT_RETURN_VOID(env,
16 status == napi_ok || status == napi_pending_exception,
17 "Unexpected status for napi_call_function");
18 NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, *ref));
19 free(ref);
20 }
21
MyObject(napi_env env,napi_callback_info info)22 static napi_value MyObject(napi_env env, napi_callback_info info) {
23 napi_value js_this;
24 napi_ref* ref = malloc(sizeof(*ref));
25 NAPI_CALL(env, napi_get_cb_info(env, info, NULL, NULL, &js_this, NULL));
26 NAPI_CALL(env, napi_wrap(env, js_this, ref, MyObject_fini, NULL, ref));
27 return NULL;
28 }
29
NAPI_MODULE_INIT()30 NAPI_MODULE_INIT() {
31 napi_value ctor;
32 NAPI_CALL(
33 env, napi_define_class(
34 env, "MyObject", NAPI_AUTO_LENGTH, MyObject, NULL, 0, NULL, &ctor));
35 NAPI_CALL(env, napi_set_named_property(env, exports, "MyObject", ctor));
36 return exports;
37 }
38