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