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 <cstddef>
17
18 #include "napi/native_api.h"
19 #include "napi/native_node_api.h"
20
21 extern const char _binary_calc_js_start[];
22 extern const char _binary_calc_js_end[];
23
24 /*
25 * Sync callback
26 */
Add(napi_env env,napi_callback_info info)27 static napi_value Add(napi_env env, napi_callback_info info)
28 {
29 size_t requireArgc = 2;
30 size_t argc = 2;
31 napi_value args[2] = { nullptr };
32 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
33
34 NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments");
35
36 napi_valuetype valuetype0;
37 NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0));
38
39 napi_valuetype valuetype1;
40 NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1));
41
42 NAPI_ASSERT(env, valuetype0 == napi_number && valuetype1 == napi_number, "Wrong argument type. Numbers expected.");
43
44 double value0;
45 NAPI_CALL(env, napi_get_value_double(env, args[0], &value0));
46
47 double value1;
48 NAPI_CALL(env, napi_get_value_double(env, args[1], &value1));
49
50 napi_value sum;
51 NAPI_CALL(env, napi_create_double(env, value0 + value1, &sum));
52
53 return sum;
54 }
55
56 /*
57 * function for module exports
58 */
Init(napi_env env,napi_value exports)59 static napi_value Init(napi_env env, napi_value exports)
60 {
61 /*
62 * Properties define
63 */
64 napi_property_descriptor desc[] = {
65 DECLARE_NAPI_FUNCTION("add", Add),
66 };
67 NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
68 return exports;
69 }
70
NAPI_calc_GetJSCode(const char ** buf,int * bufLen)71 extern "C" __attribute__((visibility("default"))) void NAPI_calc_GetJSCode(const char** buf, int* bufLen)
72 {
73 if (buf != nullptr) {
74 *buf = _binary_calc_js_start;
75 }
76
77 if (bufLen != nullptr) {
78 *bufLen = _binary_calc_js_end - _binary_calc_js_start;
79 }
80 }
81
82 /*
83 * Module define
84 */
85 static napi_module calcModule = {
86 .nm_version = 1,
87 .nm_flags = 0,
88 .nm_filename = nullptr,
89 .nm_register_func = Init,
90 .nm_modname = "calc",
91 .nm_priv = ((void*)0),
92 .reserved = { 0 },
93 };
94 /*
95 * Module register function
96 */
CalcRegisterModule(void)97 extern "C" __attribute__((constructor)) void CalcRegisterModule(void)
98 {
99 napi_module_register(&calcModule);
100 }
101