• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 使用Node-API接口进行primitive类相关开发
2<!--Kit: NDK-->
3<!--Subsystem: arkcompiler-->
4<!--Owner: @xliu-huanwei; @shilei123; @huanghello-->
5<!--Designer: @shilei123-->
6<!--Tester: @kirl75; @zsw_zhushiwei-->
7<!--Adviser: @fang-jinxu-->
8
9## 简介
10
11使用Node-API接口,开发人员可以在Node-API模块中与ArkTS对象交互,进行数据转换和获取特定对象。这些操作在不同场景中发挥重要作用,使开发人员能够更灵活地处理ArkTS值和对象。
12
13## 基本概念
14
15使用Node-API操作ArkTS对象时,需要了解一些基本概念。
16
17- **ArkTS值到C/C++类型的转换:** 在Node-API模块中,可以使用Node-API函数将ArkTS值转换为C/C++的数据类型,如将ArkTS数值转换为C/C++的整数、将ArkTS字符串转换为C/C++的字符数组等。同样,也可以将C/C++的数据类型转换为ArkTS值,以便将结果返回给ArkTS代码。
18
19## 场景和功能介绍
20
21以下接口用于从C/C++代码中与ArkTS交互,传递数据并执行操作
22| 接口 | 描述 |
23| -------- | -------- |
24| napi_coerce_to_bool | 将给定的ArkTS value强转为ArkTS boolean值。 |
25| napi_coerce_to_number | 将给定的ArkTS value强转成ArkTS number。 |
26| napi_coerce_to_object | 将给定的ArkTS value强转成ArkTS Object。 |
27| napi_coerce_to_string | 将给定的ArkTS value强转成ArkTS string。 |
28| napi_get_boolean | 将给定的C boolean值,获取ArkTS boolean值。 |
29| napi_get_value_bool | 根据给定的ArkTS boolean值,获取等价的C/C++布尔值。 |
30| napi_get_global | 获取全局ArkTS对象,以便在C/C++中访问和操纵全局对象。 |
31| napi_get_null | 获取ArkTS null。 |
32| napi_get_undefined | 获取ArkTS undefined。 |
33
34## 使用示例
35
36Node-API接口开发流程请参考[使用Node-API实现跨语言交互开发流程](use-napi-process.md),本文仅展示接口对应的C++及ArkTS相关代码。
37
38### napi_coerce_to_bool
39
40用于将给定的ArkTS value强转成ArkTS boolean值。
41
42cpp部分代码
43
44```cpp
45#include "napi/native_api.h"
46
47static napi_value CoerceToBool(napi_env env, napi_callback_info info)
48{
49    // 获取并解析传进的参数
50    size_t argc = 1;
51    napi_value args[1] = {nullptr};
52    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
53    // 将传入的值转换为布尔值
54    napi_value result = nullptr;
55    napi_coerce_to_bool(env, args[0], &result);
56    //返回强转之后的ArkTS boolean值
57    return result;
58}
59```
60<!-- @[napi_coerce_to_bool](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/napi_init.cpp) -->
61
62接口声明
63
64```ts
65// index.d.ts
66export const coerceToBool: <T>(data: T) => boolean;
67```
68<!-- @[napi_coerce_to_bool_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/types/libentry/Index.d.ts) -->
69
70ArkTS侧示例代码
71
72```ts
73import { hilog } from '@kit.PerformanceAnalysisKit';
74import testNapi from 'libentry.so';
75
76let value = testNapi.coerceToBool<number>(0);
77let str = testNapi.coerceToBool<string>('111111111');
78let obj = new Object();
79let res = testNapi.coerceToBool<Object>(obj);
80let result = testNapi.coerceToBool<null>(null);
81// false
82hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_bool:%{public}s', value);
83// true
84hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_bool:%{public}s', str);
85// true
86hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_bool:%{public}s', res);
87// false
88hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_bool:%{public}s', result);
89```
90<!-- @[ark_napi_coerce_to_bool](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/ets/pages/Index.ets) -->
91
92### napi_coerce_to_number
93
94将给定的ArkTS value强转成ArkTS number。
95
96cpp部分代码
97
98```cpp
99#include "napi/native_api.h"
100
101static napi_value CoerceToNumber(napi_env env, napi_callback_info info)
102{
103    // 获取并解析传进的参数
104    size_t argc = 1;
105    napi_value args[1] = {nullptr};
106    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
107    // 将传入的值转换为number值
108    napi_value result = nullptr;
109    napi_coerce_to_number(env, args[0], &result);
110    return result;
111}
112```
113<!-- @[napi_coerce_to_number](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/napi_init.cpp) -->
114
115接口声明
116
117```ts
118// index.d.ts
119export const coerceToNumber: <T>(data: T) => number;
120```
121<!-- @[napi_coerce_to_number_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/types/libentry/Index.d.ts) -->
122
123ArkTS侧示例代码
124
125```ts
126import { hilog } from '@kit.PerformanceAnalysisKit';
127import testNapi from 'libentry.so';
128
129let value = testNapi.coerceToNumber<string>('2556');
130let str = testNapi.coerceToNumber<string>('sssss');
131let bool = testNapi.coerceToNumber<boolean>(true);
132hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_number:%{public}d', value);
133hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_number:%{public}d', str);    // 返回的为NAN
134hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_number:%{public}d', bool);   // 返回的是1
135```
136<!-- @[ark_napi_coerce_to_number](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/ets/pages/Index.ets) -->
137
138### napi_coerce_to_object
139
140用于将给定的ArkTS value强转成ArkTS Object。
141
142cpp部分代码:
143
144```cpp
145#include "napi/native_api.h"
146
147static napi_value CoerceToObject(napi_env env, napi_callback_info info)
148{
149    // 获取并解析传进的参数
150    size_t argc = 1;
151    napi_value args[1] = {nullptr};
152    napi_value obj = nullptr;
153    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
154    // 将传入的值转换为Object值
155    napi_coerce_to_object(env, args[0], &obj);
156    return obj;
157}
158```
159<!-- @[napi_coerce_to_object](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/napi_init.cpp) -->
160
161接口声明
162
163```ts
164// index.d.ts
165export const coerceToObject: <T>(data: T) => Object;
166```
167<!-- @[napi_coerce_to_object_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/types/libentry/Index.d.ts) -->
168
169ArkTS侧示例代码
170
171```ts
172import { hilog } from '@kit.PerformanceAnalysisKit';
173import testNapi from 'libentry.so';
174
175let value = testNapi.coerceToObject<string>('222222');
176let result = testNapi.coerceToObject<number>(111);
177hilog.info(0x0000, 'testTag', 'Node-API coerceToObject:%{public}s.', typeof result);
178if (typeof value === 'object') {
179  hilog.info(0x0000, 'testTag', 'Node-API The value is an object.');
180} else {
181  hilog.info(0x0000, 'testTag', 'Node-API The value is not an object.');
182}
183```
184<!-- @[ark_napi_coerce_to_object](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/ets/pages/Index.ets) -->
185
186### napi_coerce_to_string
187
188用于将给定的ArkTS value强转成ArkTS string。
189
190cpp部分代码
191
192```cpp
193#include "napi/native_api.h"
194
195static napi_value CoerceToString(napi_env env, napi_callback_info info)
196{
197    // 获取并解析传进的参数
198    size_t argc = 1;
199    napi_value args[1] = {nullptr};
200    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
201    // 将传入的值转换为string
202    napi_value str = nullptr;
203    napi_coerce_to_string(env, args[0], &str);
204    return str;
205}
206```
207<!-- @[napi_coerce_to_string](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/napi_init.cpp) -->
208
209接口声明
210
211```ts
212// index.d.ts
213export const coerceToString: <T>(data: T) => string;
214```
215<!-- @[napi_coerce_to_string_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/types/libentry/Index.d.ts) -->
216
217ArkTS侧示例代码
218
219```ts
220import { hilog } from '@kit.PerformanceAnalysisKit';
221import testNapi from 'libentry.so';
222
223let value = testNapi.coerceToString<number>(212);
224let obj = new Object();
225let res = testNapi.coerceToString<Object>(obj);
226let bool = testNapi.coerceToString<boolean>(false);
227hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_string:%{public}s', value);
228hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_string:%{public}s', typeof res);
229hilog.info(0x0000, 'testTag', 'Test Node-API napi_coerce_to_string:%{public}s', bool);
230```
231<!-- @[ark_napi_coerce_to_string](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/ets/pages/Index.ets) -->
232
233### napi_get_boolean
234
235根据给定的C boolean值,获取等价的ArkTS boolean值。
236
237cpp部分代码
238
239```cpp
240#include "napi/native_api.h"
241#include "hilog/log.h"
242
243static napi_value GetBoolean(napi_env env, napi_callback_info info)
244{
245    // 传入两个参数并解析
246    size_t argc = 2;
247    napi_value argv[2];
248    napi_valuetype data, value;
249    napi_status status = napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
250    if (status != napi_ok) {
251        OH_LOG_ERROR(LOG_APP, "napi_get_cb_info failed");
252        return nullptr;
253    }
254    // 判断两个参数类型值
255    napi_typeof(env, argv[0], &data);
256    napi_typeof(env, argv[1], &value);
257
258    napi_value returnValue = nullptr;
259    // 判断两个类型值是否相等,获取结果的布尔值
260    status = napi_get_boolean(env, data == value, &returnValue);
261    if (status != napi_ok) {
262        OH_LOG_ERROR(LOG_APP, "napi_get_boolean failed");
263        return nullptr;
264    }
265    // 返回结果
266    return returnValue;
267}
268```
269<!-- @[napi_get_boolean](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/napi_init.cpp) -->
270
271接口声明
272
273```ts
274// index.d.ts
275export const getBoolean: <T>(data: T, value: string) => boolean;
276```
277<!-- @[napi_get_boolean_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/types/libentry/Index.d.ts) -->
278
279ArkTS侧示例代码
280
281```ts
282import { hilog } from '@kit.PerformanceAnalysisKit';
283import testNapi from 'libentry.so';
284
285let value = testNapi.getBoolean<number>(1, '1');
286let data = testNapi.getBoolean<string>('sss', '1');
287hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_boolean:%{public}s', value);
288hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_boolean:%{public}s', data);
289```
290<!-- @[ark_napi_get_boolean](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/ets/pages/Index.ets) -->
291
292### napi_get_value_bool
293
294使用此函数将ArkTS中的布尔值转换为等价的C布尔值。
295
296cpp部分代码
297
298```cpp
299#include "napi/native_api.h"
300#include "hilog/log.h"
301
302static napi_value GetValueBool(napi_env env, napi_callback_info info)
303{
304    size_t argc = 1;
305    napi_value args[1] = {nullptr};
306
307    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
308    bool bool_c = false;
309    napi_status status = napi_get_value_bool(env, args[0], &bool_c);
310    if (status == napi_boolean_expected) {
311        // 如果napi_get_value_bool成功会返回napi_ok,如果传入一个非布尔值则会返回napi_boolean_expected
312        return nullptr;
313    }
314    napi_value boolNapi = nullptr;
315    status = napi_get_boolean(env, bool_c, &boolNapi);
316    if (status != napi_ok) {
317        OH_LOG_ERROR(LOG_APP, "napi_get_boolean failed");
318        return nullptr;
319    }
320    return boolNapi;
321}
322```
323<!-- @[napi_get_value_bool](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/napi_init.cpp) -->
324
325接口声明
326
327```ts
328// index.d.ts
329export const getValueBool: (value: boolean | string) => boolean | undefined;
330```
331<!-- @[napi_get_value_bool_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/types/libentry/Index.d.ts) -->
332
333ArkTS侧示例代码
334
335```ts
336import { hilog } from '@kit.PerformanceAnalysisKit';
337import testNapi from 'libentry.so';
338
339// 分别传入布尔值和非布尔值检测接口,传入布尔值将返回原布尔值,传入其他类型返回undefined
340hilog.info(0x0000, 'Node-API', 'get_value_bool_not_bool %{public}s', testNapi.getValueBool('你好123'));
341hilog.info(0x0000, 'Node-API', 'get_value_bool_true %{public}s', testNapi.getValueBool(true));
342hilog.info(0x0000, 'Node-API', 'get_value_bool_false %{public}s', testNapi.getValueBool(false));
343```
344<!-- @[ark_napi_get_value_bool](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/ets/pages/Index.ets) -->
345
346### napi_get_global
347
348获取全局ArkTS对象。此函数用于获取表示ArkTS全局对象的napi_value,使C/C++模块能与ArkTS运行时的全局对象交互。
349
350cpp部分代码
351
352```cpp
353#include "napi/native_api.h"
354
355static napi_value GetGlobal(napi_env env, napi_callback_info info)
356{
357    napi_value global = nullptr;
358    // 获取global对象
359    napi_get_global(env, &global);
360    return global;
361}
362```
363<!-- @[napi_get_global](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/napi_init.cpp) -->
364
365接口声明
366
367```ts
368// index.d.ts
369export const getGlobal: () => Object;
370```
371<!-- @[napi_get_global_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/types/libentry/Index.d.ts) -->
372
373ArkTS侧示例代码
374
375```ts
376import { hilog } from '@kit.PerformanceAnalysisKit';
377import testNapi from 'libentry.so';
378
379let globalObj = testNapi.getGlobal();
380// 判断获取的global是否具有global的自身属性
381hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_global:%{public}s', globalObj.hasOwnProperty!("undefined"));
382```
383<!-- @[ark_napi_get_global](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/ets/pages/Index.ets) -->
384
385### napi_get_null
386
387获取ArkTS中的null值。
388
389cpp部分代码
390
391```cpp
392#include "napi/native_api.h"
393
394static napi_value GetNull(napi_env env, napi_callback_info info)
395{
396    napi_value nullValue = nullptr;
397    napi_get_null(env, &nullValue);
398    return nullValue;
399}
400```
401<!-- @[napi_get_null](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/napi_init.cpp) -->
402
403接口声明
404
405```ts
406// index.d.ts
407export const getNull: () => null;
408```
409<!-- @[napi_get_null_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/types/libentry/Index.d.ts) -->
410
411ArkTS侧示例代码
412
413```ts
414import { hilog } from '@kit.PerformanceAnalysisKit';
415import testNapi from 'libentry.so';
416
417let value = testNapi.getNull();
418hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_null:%{public}s', value);
419```
420<!-- @[ark_napi_get_null](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/ets/pages/Index.ets) -->
421
422### napi_get_undefined
423
424获取ArkTS中的undefined值。
425
426cpp部分代码
427
428```cpp
429#include "napi/native_api.h"
430
431static napi_value GetUndefined(napi_env env, napi_callback_info info)
432{
433    // 获取并解析传进的参数
434    size_t argc = 1;
435    napi_value args[1] = {nullptr};
436    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
437
438    napi_value value = nullptr;
439    napi_get_undefined(env, &value);
440    // 判断传入参数的类型与undefined值的类型是否一致
441    bool isEqual = false;
442    napi_strict_equals(env, args[0], value, &isEqual);
443    // 参数与undefined值相等
444    napi_value result = nullptr;
445    // 返回判断类型之后的结果,相等返回为true,不等则为false
446    napi_get_boolean(env, isEqual, &result);
447    return result;
448}
449```
450<!-- @[napi_get_undefined](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/napi_init.cpp) -->
451
452接口声明
453
454```ts
455// index.d.ts
456export const getUndefined: (value: undefined) => boolean;
457```
458<!-- @[napi_get_undefined_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/cpp/types/libentry/Index.d.ts) -->
459
460ArkTS侧示例代码
461
462```ts
463import { hilog } from '@kit.PerformanceAnalysisKit';
464import testNapi from 'libentry.so';
465
466let data: undefined = undefined;
467let value = testNapi.getUndefined(data);
468hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_undefined:%{public}s', value);
469```
470<!-- @[ark_napi_get_undefined](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIPrimitive/entry/src/main/ets/pages/Index.ets) -->
471
472以上代码如果要在native cpp中打印日志,需在CMakeLists.txt文件中添加以下配置信息(并添加头文件:#include "hilog/log.h"):
473
474```text
475// CMakeLists.txt
476add_definitions( "-DLOG_DOMAIN=0xd0d0" )
477add_definitions( "-DLOG_TAG=\"testTag\"" )
478target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so)
479```
480