1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "napi/native_api.h"
17 #include "napi/native_node_api.h"
18
19 extern const char _binary_calc_js_start[];
20 extern const char _binary_calc_js_end[];
21
22 /*
23 * Sync callback
24 */
Add(napi_env env,napi_callback_info info)25 static napi_value Add(napi_env env, napi_callback_info info)
26 {
27 size_t requireArgc = 2;
28 size_t argc = 2;
29 napi_value args[2] = { nullptr };
30 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
31
32 NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments");
33
34 napi_valuetype valuetype0;
35 NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0));
36
37 napi_valuetype valuetype1;
38 NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1));
39
40 NAPI_ASSERT(env, valuetype0 == napi_number && valuetype1 == napi_number, "Wrong argument type. Numbers expected.");
41
42 double value0;
43 NAPI_CALL(env, napi_get_value_double(env, args[0], &value0));
44
45 double value1;
46 NAPI_CALL(env, napi_get_value_double(env, args[1], &value1));
47
48 napi_value sum;
49 NAPI_CALL(env, napi_create_double(env, value0 + value1, &sum));
50
51 return sum;
52 }
53
54 /*
55 * function for module exports
56 */
Init(napi_env env,napi_value exports)57 static napi_value Init(napi_env env, napi_value exports)
58 {
59 /*
60 * Properties define
61 */
62 napi_property_descriptor desc[] = {
63 DECLARE_NAPI_FUNCTION("add", Add),
64 };
65 NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
66 return exports;
67 }
68
NAPI_calc_GetJSCode(const char ** buf,int * bufLen)69 extern "C" __attribute__((visibility("default"))) void NAPI_calc_GetJSCode(const char** buf, int* bufLen)
70 {
71 if (buf != nullptr) {
72 *buf = _binary_calc_js_start;
73 }
74
75 if (bufLen != nullptr) {
76 *bufLen = _binary_calc_js_end - _binary_calc_js_start;
77 }
78 }
79
80 /*
81 * Module define
82 */
83 static napi_module calcModule = {
84 .nm_version = 1,
85 .nm_flags = 0,
86 .nm_filename = nullptr,
87 .nm_register_func = Init,
88 .nm_modname = "calc",
89 .nm_priv = ((void*)0),
90 .reserved = { 0 },
91 };
92 /*
93 * Module register function
94 */
CalcRegisterModule(void)95 extern "C" __attribute__((constructor)) void CalcRegisterModule(void)
96 {
97 napi_module_register(&calcModule);
98 }