1 /*
2 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development 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 "common.h"
17 #include "javascriptapi.h"
18
19 static const char *TAG = "[javascriptapi_values";
20
testNapiCreateInt32(napi_env env,napi_callback_info info)21 napi_value testNapiCreateInt32(napi_env env, napi_callback_info info)
22 {
23 // pages/javascript/jsvalues/napicreateint32
24 // 获取参数数量
25 size_t argc = 1;
26 // 准备接收参数的变量
27 napi_value argv[1];
28 int32_t intValue;
29 napi_value result;
30 napi_status status;
31 const napi_extended_error_info *extended_error_info;
32
33 // 获取回调函数的参数信息
34 status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
35 if (status != napi_ok) {
36 getErrMsg(status, env, extended_error_info, "Failed to get callback info", TAG);
37 return NULL;
38 }
39
40 // 检查参数数量是否符合预期
41 if (argc != 1) {
42 napi_throw_error(env, NULL, "Expected exactly one argument");
43 return NULL;
44 }
45
46 // 从JavaScript值中提取出整数
47 status = napi_get_value_int32(env, argv[0], &intValue);
48 if (status != napi_ok) {
49 getErrMsg(status, env, extended_error_info, "Failed to convert argument to int32", TAG);
50 return NULL;
51 }
52
53 // 检查整数是否为3
54 if (intValue != 3) {
55 // 如果不是3,我们可以返回一个错误信息
56 napi_throw_error(env, NULL, "The number is not 3");
57 return NULL;
58 }
59
60 // 使用提取的整数值创建一个新的napi_value
61 status = napi_create_int32(env, intValue, &result);
62 if (status != napi_ok) {
63 getErrMsg(status, env, extended_error_info, "Failed to create int32 value", TAG);
64 return NULL;
65 }
66
67 // 返回创建的napi_value
68 return result;
69 }
70