1 #include <js_native_api.h>
2 #include "../common.h"
3 #include <string.h>
4
RunCallback(napi_env env,napi_callback_info info)5 static napi_value RunCallback(napi_env env, napi_callback_info info) {
6 size_t argc = 2;
7 napi_value args[2];
8 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
9
10 NAPI_ASSERT(env, argc == 1,
11 "Wrong number of arguments. Expects a single argument.");
12
13 napi_valuetype valuetype0;
14 NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0));
15 NAPI_ASSERT(env, valuetype0 == napi_function,
16 "Wrong type of arguments. Expects a function as first argument.");
17
18 napi_valuetype valuetype1;
19 NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1));
20 NAPI_ASSERT(env, valuetype1 == napi_undefined,
21 "Additional arguments should be undefined.");
22
23 napi_value argv[1];
24 const char* str = "hello world";
25 size_t str_len = strlen(str);
26 NAPI_CALL(env, napi_create_string_utf8(env, str, str_len, argv));
27
28 napi_value global;
29 NAPI_CALL(env, napi_get_global(env, &global));
30
31 napi_value cb = args[0];
32 NAPI_CALL(env, napi_call_function(env, global, cb, 1, argv, NULL));
33
34 return NULL;
35 }
36
RunCallbackWithRecv(napi_env env,napi_callback_info info)37 static napi_value RunCallbackWithRecv(napi_env env, napi_callback_info info) {
38 size_t argc = 2;
39 napi_value args[2];
40 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
41
42 napi_value cb = args[0];
43 napi_value recv = args[1];
44 NAPI_CALL(env, napi_call_function(env, recv, cb, 0, NULL, NULL));
45 return NULL;
46 }
47
48 EXTERN_C_START
Init(napi_env env,napi_value exports)49 napi_value Init(napi_env env, napi_value exports) {
50 napi_property_descriptor desc[2] = {
51 DECLARE_NAPI_PROPERTY("RunCallback", RunCallback),
52 DECLARE_NAPI_PROPERTY("RunCallbackWithRecv", RunCallbackWithRecv),
53 };
54 NAPI_CALL(env, napi_define_properties(env, exports, 2, desc));
55 return exports;
56 }
57 EXTERN_C_END
58