1# 使用Node-API接口进行array相关开发 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接口进行array相关开发时,调用相关接口可以在Node-API模块中直接操作和处理ArkTS中的数组。 12 13## 基本概念 14 15使用Node-API接口进行数组(array)相关开发时,涉及的基本概念主要包括数组的创建、访问、修改、遍历以及与数组相关的操作。这些概念对于理解如何在Node-API模块中与ArkTS数组交互非常重要。以下是一些关键概念: 16 17- **数组的创建**:在Node-API模块中需要创建一个新的ArkTS数组,可以使用napi_create_array接口创建数组,将数组传递给ArkTS层。 18- **数组相关操作**:在Node-API模块中通过对应的接口获取ArkTS数组的长度、检索指定索引处的元素以及设置指定索引处的元素值,从而实现Node-API模块与ArkTS数组的交互。 19- **TypedArray**:ArkTS中的TypedArray是一种用来描述二进制数据的类数组数据视图,可以简单理解为一种指定元素类型的数组,TypedArray没有直接构造器,但是可以用它的子类构造器构造TypedArray类型的数据。TypedArray的子类有:Int8Array、Uint8Array、Uint8ClampedArray、Int16Array、Int32Array等。 20- **DataView**:DataView是ArkTS中的一种视图,是可以从ArrayBuffer对象中读写多种数值类型的底层接口。 21- **ArrayBuffer**:ArrayBuffer是固定长度的二进制数据缓冲区。 22 23## 场景和功能介绍 24 25使用Node-API接口进行数组相关开发时,可以处理各种涉及ArkTS数组的操作和交互场景。以下是几个具体的使用场景介绍: 26| 接口 | 描述 | 27| -------- | -------- | 28| napi_create_array | 用于在Node-API模块中向ArkTS层创建一个ArkTS数组对象。 | 29| napi_create_array_with_length | 用于在Node-API模块中向ArkTS层创建指定长度的ArkTS数组时。 | 30| napi_get_array_length | 用于在Node-API模块中获取ArkTS数组对象的长度。 | 31| napi_is_array | 用于在Node-API模块中判断一个napi_value值是否为数组。 | 32| napi_set_element | 用于在Node-API模块中对ArkTS数组对象的特定索引处设置一个值。 | 33| napi_get_element | 用于在Node-API模块中从ArkTS数组对象的特定索引处获取一个值。 | 34| napi_has_element | 用于在Node-API模块中判断ArkTS数组对象请求索引处是否包含元素。 | 35| napi_delete_element | 用于在Node-API模块中从ArkTS数组对象中删除请求索引对应的元素。 | 36| napi_create_typedarray | 用于在Node-API模块中创建指定类型的TypedArray,例如Uint8Array、Int32Array等,通常用于将Node-API模块中的数据转换为ArkTS中的TypedArray,以便进行高性能的数据处理操作。 | 37| napi_is_typedarray | 用于在Node-API模块中判断一个给定的napi_value是否为TypedArray对象。 | 38| napi_get_typedarray_info | 用于在Node-API模块中获得某个TypedArray的各种属性。 | 39| napi_create_dataview | 用于在Node-API模块中创建一个DataView对象,可以访问和操作二进制数据。 | 40| napi_is_dataview | 用于在Node-API模块中判断给定的napi_value是否为ArkTS中的DataView对象。 | 41| napi_get_dataview_info | 用于在Node-API模块中获得某个DataView的各种属性。 | 42 43## 使用示例 44 45Node-API接口开发流程参考[使用Node-API实现跨语言交互开发流程](use-napi-process.md),本文仅对接口对应C++及ArkTS相关代码进行展示。具体使用见示例。 46 47### napi_create_array 48 49用于在Node-API模块中创建一个ArkTS数组。 50 51cpp部分代码 52 53```cpp 54#include "napi/native_api.h" 55 56static constexpr int INT_NUM_5 = 5; // 数组长度 57 58static napi_value CreateArray(napi_env env, napi_callback_info info) 59{ 60 // 创建一个空数组 61 napi_value jsArray = nullptr; 62 napi_create_array(env, &jsArray); 63 // 将创建好的数组进行赋值 64 for (int i = 0; i < INT_NUM_5; i++) { 65 napi_value element; 66 napi_create_int32(env, i, &element); 67 napi_set_element(env, jsArray, i, element); 68 } 69 // 返回已创建好的数组 70 return jsArray; 71} 72``` 73<!-- @[napi_create_array](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 74 75接口声明 76 77```ts 78// index.d.ts 79export const createArray: () => number[]; 80``` 81<!-- @[napi_create_array_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 82 83ArkTS侧示例代码 84 85```ts 86import { hilog } from '@kit.PerformanceAnalysisKit'; 87import testNapi from 'libentry.so'; 88 89hilog.info(0x0000, 'testTag', 'Test Node-API napi_create_array:%{public}s', JSON.stringify(testNapi.createArray())); 90``` 91<!-- @[ark_napi_create_array](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 92 93### napi_create_array_with_length 94 95用于在Node-API模块中创建一个具有指定长度的ArkTS数组。 96 97cpp部分代码 98 99```cpp 100#include "napi/native_api.h" 101 102static napi_value CreateArrayWithLength(napi_env env, napi_callback_info info) 103{ 104 // 获取ArkTS侧传入的参数 105 size_t argc = 1; 106 napi_value argv[1] = {nullptr}; 107 napi_value jsArray = nullptr; 108 napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); 109 // 获取传递的数组长度 110 int32_t length = 0; 111 napi_get_value_int32(env, argv[0], &length); 112 // 使用napi_create_array_with_length创建指定长度的数组 113 napi_create_array_with_length(env, length, &jsArray); 114 // 返回数组 115 return jsArray; 116} 117``` 118<!-- @[napi_create_array_with_length](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 119 120接口声明 121 122```ts 123// index.d.ts 124export const createArrayWithLength: (length: number) => void[]; 125``` 126<!-- @[napi_create_array_with_length_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 127 128ArkTS侧示例代码 129 130```ts 131import { hilog } from '@kit.PerformanceAnalysisKit'; 132import testNapi from 'libentry.so'; 133 134let array = testNapi.createArrayWithLength(6); 135hilog.info(0x0000, 'testTag', 'Test Node-API napi_create_array_with_length:%{public}d', array.length); 136``` 137<!-- @[ark_napi_create_array_with_length](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 138 139### napi_get_array_length 140 141获取给定array的长度。 142 143cpp部分代码 144 145```cpp 146#include "napi/native_api.h" 147 148static napi_value GetArrayLength(napi_env env, napi_callback_info info) 149{ 150 // 获取ArkTS侧传入的参数 151 size_t argc = 1; 152 napi_value args[1] = {nullptr}; 153 napi_value result; 154 uint32_t length; 155 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 156 // 检查参数是否为数组 157 bool is_array; 158 napi_is_array(env, args[0], &is_array); 159 if (!is_array) { 160 napi_throw_error(env, nullptr, "Argument must be an array"); 161 return nullptr; 162 } 163 napi_get_array_length(env, args[0], &length); 164 // 创建返回值 165 napi_create_uint32(env, length, &result); 166 return result; 167} 168``` 169<!-- @[napi_get_array_length](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 170 171接口声明 172 173```ts 174// index.d.ts 175export const getArrayLength: (arr: Array<any>) => number | undefined; 176``` 177<!-- @[napi_get_array_length_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 178 179ArkTS侧示例代码 180 181```ts 182import { hilog } from '@kit.PerformanceAnalysisKit'; 183import testNapi from 'libentry.so'; 184 185const arr = [0, 1, 2, 3, 4, 5]; 186hilog.info(0x0000, 'testTag', 'Test Node-API get_array_length:%{public}d', testNapi.getArrayLength(arr)); 187``` 188<!-- @[ark_napi_get_array_length](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 189 190### napi_is_array 191 192判断给定ArkTS值是否为数组。 193 194cpp部分代码 195 196```cpp 197#include "napi/native_api.h" 198 199static napi_value IsArray(napi_env env, napi_callback_info info) 200{ 201 // 获取ArkTS侧传入的参数 202 size_t argc = 1; 203 napi_value args[1] = {nullptr}; 204 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 205 // 调用napi_is_array接口判断给定入参是否为array数组 206 bool result; 207 napi_status status; 208 status = napi_is_array(env, args[0], &result); 209 if (status != napi_ok) { 210 napi_throw_error(env, nullptr, "Node-API napi_is_array fail"); 211 return nullptr; 212 } 213 // 将结果转成napi_value类型返回 214 napi_value returnValue; 215 napi_get_boolean(env, result, &returnValue); 216 217 return returnValue; 218} 219``` 220<!-- @[napi_is_array](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 221 222接口声明 223 224```ts 225// index.d.ts 226export const isArray: <T>(data: Array<T> | T) => boolean | undefined; 227``` 228<!-- @[napi_is_array_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 229 230ArkTS侧示例代码 231 232```ts 233import { hilog } from '@kit.PerformanceAnalysisKit'; 234import testNapi from 'libentry.so'; 235try { 236 let value = new Array<number>(1); 237 let data = "123"; 238 hilog.info(0x0000, 'testTag', 'Test Node-API napi_is_array: %{public}s', testNapi.isArray<number>(value)); 239 hilog.info(0x0000, 'testTag', 'Test Node-API napi_is_array: %{public}s', testNapi.isArray<string>(data)); 240} catch (error) { 241 hilog.error(0x0000, 'testTag', 'Test Node-API napi_is_array error: %{public}s', error.message); 242} 243``` 244<!-- @[ark_napi_is_array](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 245 246### napi_set_element 247 248用于在ArkTS数组中设置指定索引位置的元素。 249对于以索引值为键的object,可以使用napi_set_element来设置属性值。 250 251cpp部分代码 252 253```cpp 254#include "napi/native_api.h" 255 256static constexpr int INT_ARG_2 = 2; // 入参索引 257 258static napi_value NapiSetElement(napi_env env, napi_callback_info info) 259{ 260 // 获取ArkTS侧传入的参数 261 size_t argc = 3; 262 napi_value args[3] = {nullptr}; 263 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 264 // 检查第一个参数是否为数组 265 bool isArr = false; 266 napi_is_array(env, args[0], &isArr); 267 if (!isArr) { 268 napi_throw_error(env, nullptr, "Argument should be an object of type array"); 269 return nullptr; 270 } 271 // 获取要设置的元素索引 272 double index = 0; 273 napi_status status = napi_get_value_double(env, args[1], &index); 274 if (status != napi_ok || index < 0) { 275 napi_throw_error(env, nullptr, "The index should be a non-negative number"); 276 return nullptr; 277 } 278 // 将传入的值设置到数组指定索引位置 279 napi_set_element(env, args[0], static_cast<uint32_t>(index), args[INT_ARG_2]); 280 281 return nullptr; 282} 283``` 284<!-- @[napi_set_element](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 285 286接口声明 287 288```ts 289export const napiSetElement: <T>(arr: Array<T>, index: number, value: T) => void; 290``` 291<!-- @[napi_set_element_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 292 293ArkTS侧示例代码 294 295```ts 296import { hilog } from '@kit.PerformanceAnalysisKit'; 297import testNapi from 'libentry.so'; 298try { 299 let arr = [10, 20, 30]; 300 testNapi.napiSetElement<number | string>(arr, 1, 'newElement'); 301 testNapi.napiSetElement<number | string>(arr, 2, 50); 302 hilog.info(0x0000, 'testTag', 'Test Node-API napi_set_element arr: %{public}s', arr.toString()); 303 hilog.info(0x0000, 'testTag', 'Test Node-API napi_set_element arr[3]: %{public}s', arr[3]); 304 interface MyObject { 305 first: number; 306 second: number; 307 } 308 let obj: MyObject = { 309 first: 1, 310 second: 2 311 }; 312 testNapi.napiSetElement<number | string | Object>(arr, 4, obj); 313 let objAsString = JSON.stringify(arr[4]); 314 hilog.info(0x0000, 'testTag', 'Test Node-API napi_set_element arr[4]: %{public}s', objAsString); 315} catch (error) { 316 hilog.error(0x0000, 'testTag', 'Test Node-API napi_set_element error: %{public}s', error.message); 317} 318``` 319<!-- @[ark_napi_set_element](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 320 321### napi_get_element 322 323用于从ArkTS数组中获取请求索引位置的元素值。请求索引值应在数组的有效范围内,如果索引超出数组长度,函数会返回undefined。 324 325cpp部分代码 326 327```cpp 328#include "napi/native_api.h" 329 330static napi_value NapiGetElement(napi_env env, napi_callback_info info) 331{ 332 // 获取ArkTS侧传入的参数 333 size_t argc = 2; 334 napi_value args[2] = {nullptr}; 335 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 336 // 获取请求元素的索引值 337 uint32_t index; 338 napi_get_value_uint32(env, args[1], &index); 339 // 获取请求索引位置的元素值并存储在result中 340 napi_value result; 341 napi_get_element(env, args[0], index, &result); 342 343 return result; 344} 345``` 346<!-- @[napi_get_element](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 347 348接口声明 349 350```ts 351// index.d.ts 352export const napiGetElement: <T>(arr: Array<T>, index: number) => number | string | Object | boolean | undefined; 353``` 354<!-- @[napi_get_element_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 355 356ArkTS侧示例代码 357 358```ts 359import { hilog } from '@kit.PerformanceAnalysisKit'; 360import testNapi from 'libentry.so'; 361 362interface MyObject { 363 first: number; 364 second: number; 365} 366let obj: MyObject = { 367 first: 1, 368 second: 2 369}; 370let arr = [10, 'hello', null, obj]; 371hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_element arr[0]: %{public}d', testNapi.napiGetElement<number | string | null | Object>(arr, 0)); 372hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_element arr[1]: %{public}s', testNapi.napiGetElement<number | string | null | Object>(arr, 1)); 373hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_element arr[2]: %{public}s', testNapi.napiGetElement<number | string | null | Object>(arr, 2)); 374hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_element arr[3]: %{public}s', testNapi.napiGetElement<number | string | null | Object>(arr, 3)); 375hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_element arr[4]: %{public}s', JSON.stringify(testNapi.napiGetElement(arr, 4))); 376hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_element arr[null]: %{public}s', testNapi.napiGetElement<number | string | null | Object>(arr, 5)); 377``` 378<!-- @[ark_napi_get_element](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 379 380### napi_has_element 381 382用于判断ArkTS数组是否具有指定索引的元素。如果索引超出了对象的有效范围,函数返回false,表示没有元素。 383 384cpp部分代码 385 386```cpp 387#include "napi/native_api.h" 388 389static napi_value NapiHasElement(napi_env env, napi_callback_info info) 390{ 391 // 获取ArkTS侧传入的参数 392 size_t argc = 2; 393 napi_value args[2] = {nullptr}; 394 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 395 // 获取要判断的元素的索引 396 uint32_t index; 397 napi_get_value_uint32(env, args[1], &index); 398 // 判断指定索引位置的元素是否存在 399 bool hasElement = true; 400 napi_has_element(env, args[0], index, &hasElement); 401 // 将bool结果转换为napi_value并返回 402 napi_value result; 403 napi_get_boolean(env, hasElement, &result); 404 return result; 405} 406``` 407<!-- @[napi_has_element](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 408 409接口声明 410 411```ts 412// index.d.ts 413export const napiHasElement: <T>(arr: Array<T>, index: number) => boolean; 414``` 415<!-- @[napi_has_element_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 416 417ArkTS侧示例代码 418 419```ts 420import { hilog } from '@kit.PerformanceAnalysisKit'; 421import testNapi from 'libentry.so'; 422 423let arr = [10, 'hello', null, 'world']; 424hilog.info(0x0000, 'testTag', 'Test Node-API napi_has_element arr[0]: %{public}s', testNapi.napiHasElement<number | string | null>(arr, 0)); 425hilog.info(0x0000, 'testTag', 'Test Node-API napi_has_element arr[7]: %{public}s', testNapi.napiHasElement<number | string | null>(arr, 7)); 426``` 427<!-- @[ark_napi_has_element](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 428 429### napi_delete_element 430 431用于从ArkTS数组对象中删除请求索引的元素。 432 433cpp部分代码 434 435```cpp 436#include "napi/native_api.h" 437 438static napi_value NapiDeleteElement(napi_env env, napi_callback_info info) 439{ 440 // 获取ArkTS侧传入的参数 441 size_t argc = 2; 442 napi_value args[2] = {nullptr}; 443 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 444 // 获取要删除的元素的索引 445 uint32_t index; 446 napi_get_value_uint32(env, args[1], &index); 447 // 尝试删除请求索引位置的元素 448 bool deleted = true; 449 napi_delete_element(env, args[0], index, &deleted); 450 // 将bool结果转换为napi_value并返回 451 napi_value result; 452 napi_get_boolean(env, deleted, &result); 453 return result; 454} 455``` 456<!-- @[napi_delete_element](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 457 458接口声明 459 460```ts 461// index.d.ts 462export const napiDeleteElement: <T>(arr: Array<T>, index: number) => boolean; 463``` 464<!-- @[napi_delete_element_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 465 466ArkTS侧示例代码 467 468```ts 469// 需要同时导入前文示例代码中的napiHasElement、napiGetElement接口 470import { hilog } from '@kit.PerformanceAnalysisKit'; 471import testNapi from 'libentry.so'; 472 473let arr = [10, 'hello', null, 'world']; 474hilog.info(0x0000, 'testTag', 'Test Node-API napi_has_element arr[0]: %{public}s', testNapi.napiHasElement<number | string | null>(arr, 0)); 475hilog.info(0x0000, 'testTag', 'Test Node-API napi_delete_element arr[0]: %{public}s', testNapi.napiDeleteElement<number | string | null>(arr, 0)); 476hilog.info(0x0000, 'testTag', 'Test Node-API napi_has_element deleted arr[0]: %{public}s', testNapi.napiHasElement<number | string | null>(arr, 0)); 477hilog.info(0x0000, 'testTag', 'Test Node-API napi_get_element arr[0]: %{public}d', testNapi.napiGetElement<number | string | null>(arr, 0)); 478``` 479<!-- @[ark_napi_delete_element](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 480 481### napi_create_typedarray 482 483用于在Node-API模块中通过现有的ArrayBuffer创建指定类型的ArkTS TypedArray。 484 485cpp部分代码 486 487```cpp 488#include "napi/native_api.h" 489 490static napi_value CreateTypedArray(napi_env env, napi_callback_info info) 491{ 492 // 获取ArkTS侧传入的参数 493 size_t argc = 1; 494 napi_value args[1] = {nullptr}; 495 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 496 int32_t typeNum = 0; 497 napi_get_value_int32(env, args[0], &typeNum); 498 napi_typedarray_type arrayType; 499 // 用于存储每个元素的大小 500 size_t elementSize = 0; 501 // 根据传递的类型值选择创建对应的类型数组 502 arrayType = static_cast<napi_typedarray_type>(typeNum); 503 switch (arrayType) { 504 case napi_int8_array: 505 case napi_uint8_array: 506 case napi_uint8_clamped_array: 507 elementSize = sizeof(int8_t); 508 break; 509 case napi_int16_array: 510 case napi_uint16_array: 511 elementSize = sizeof(int16_t); 512 break; 513 case napi_int32_array: 514 case napi_uint32_array: 515 elementSize = sizeof(int32_t); 516 break; 517 case napi_float32_array: 518 elementSize = sizeof(float); 519 break; 520 case napi_float64_array: 521 elementSize = sizeof(double); 522 break; 523 case napi_bigint64_array: 524 case napi_biguint64_array: 525 elementSize = sizeof(int64_t); 526 break; 527 default: 528 // 默认创建napi_int8_array类型 529 arrayType = napi_int8_array; 530 elementSize = sizeof(int8_t); 531 break; 532 } 533 size_t length = 3; 534 napi_value arrayBuffer = nullptr; 535 napi_value typedArray = nullptr; 536 void *data; 537 // 创建一个ArrayBuffer 538 napi_create_arraybuffer(env, length * elementSize, (void **)&data, &arrayBuffer); 539 // 根据给定类型创建TypedArray 540 napi_create_typedarray(env, arrayType, length, arrayBuffer, 0, &typedArray); 541 return typedArray; 542} 543``` 544<!-- @[napi_create_typed_array](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 545 546接口声明 547 548```ts 549// index.d.ts 550export const enum TypedArrayTypes { 551 INT8_ARRAY = 0, 552 UINT8_ARRAY, 553 UINT8_CLAMPED_ARRAY, 554 INT16_ARRAY, 555 UINT16_ARRAY, 556 INT32_ARRAY, 557 UINT32_ARRAY, 558 FLOAT32_ARRAY, 559 FLOAT64_ARRAY, 560 BIGINT64_ARRAY, 561 BIGUINT64_ARRAY, 562} 563export const createTypedArray: <T>(type: TypedArrayTypes) => T; 564``` 565<!-- @[napi_create_typed_array_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 566 567ArkTS侧示例代码 568 569```ts 570import { hilog } from '@kit.PerformanceAnalysisKit'; 571import testNapi from 'libentry.so'; 572 573// 传递要创建的类型值 574let typedArray = testNapi.createTypedArray<Int8Array>(testNapi.TypedArrayTypes["INT8_ARRAY"]); 575if (typedArray instanceof Int8Array) { 576 hilog.info(0x0000, 'testTag', ' Node-API napi_create_typedarray: Int8Array'); 577} 578let uint8Array = testNapi.createTypedArray<Uint8Array>(testNapi.TypedArrayTypes["UINT8_ARRAY"]); 579if (uint8Array instanceof Uint8Array) { 580 hilog.info(0x0000, 'testTag', ' Node-API napi_create_typedarray: Uint8Array'); 581} 582``` 583<!-- @[ark_napi_create_typed_array](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 584 585需要对use-napi-process.md中的模块初始化部分进行修改,具体见如下: 586 587```cpp 588#include <string> 589 590EXTERN_C_START 591static napi_value Init(napi_env env, napi_value exports) 592{ 593 // 定义的TypedArray类型供ArkTS侧使用,用于存放typedArrayTypes类型,使用示例见ArkTS侧的createTypedArray函数 594 napi_value typedArrayTypes; 595 napi_create_object(env, &typedArrayTypes); 596 napi_value typeIndex; 597 std::string typeKeys[] = { 598 "INT8_ARRAY", "UINT8_ARRAY", "UINT8_CLAMPED_ARRAY", "INT16_ARRAY", "UINT16_ARRAY", "INT32_ARRAY", 599 "UINT32_ARRAY", "FLOAT32_ARRAY", "FLOAT64_ARRAY", "BIGINT64_ARRAY", "BIGUINT64_ARRAY", 600 }; 601 for (int32_t i = 0; i < sizeof(typeKeys) / sizeof(typeKeys[0]); i++) { 602 napi_create_int32(env, i, &typeIndex); 603 napi_set_named_property(env, typedArrayTypes, typeKeys[i].c_str(), typeIndex); 604 } 605 napi_property_descriptor desc[] = { 606 {"createTypedArray", nullptr, CreateTypedArray, nullptr, nullptr, nullptr, napi_default, nullptr}, 607 {"TypedArrayTypes", nullptr, nullptr, nullptr, nullptr, typedArrayTypes, napi_default, nullptr} 608 }; 609 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 610 return exports; 611} 612EXTERN_C_END 613 614``` 615<!-- @[change_use_napi_process](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 616 617### napi_is_typedarray 618 619用于在Node-API模块中判断ArkTS侧给定的napi_value是否为TypedArray对象。 620 621cpp部分代码 622 623```cpp 624#include "napi/native_api.h" 625 626static napi_value IsTypedarray(napi_env env, napi_callback_info info) 627{ 628 // 获取ArkTS侧传入的参数 629 size_t argc = 1; 630 napi_value args[1] = {nullptr}; 631 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 632 // 调用napi_is_typedarray接口判断给定入参类型是否为TypedArray。 633 bool result = false; 634 napi_status status; 635 status = napi_is_typedarray(env, args[0], &result); 636 if (status != napi_ok) { 637 napi_throw_error(env, nullptr, "Node-API napi_is_typedarray fail"); 638 return nullptr; 639 } 640 // 将结果转成napi_value类型返回。 641 napi_value returnValue = nullptr; 642 napi_get_boolean(env, result, &returnValue); 643 644 return returnValue; 645} 646``` 647<!-- @[napi_is_typed_array](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 648 649接口声明 650 651```ts 652// index.d.ts 653export const isTypedarray: (data: Object) => boolean | undefined; 654``` 655<!-- @[napi_is_typed_array_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 656 657ArkTS侧示例代码 658 659```ts 660import { hilog } from '@kit.PerformanceAnalysisKit'; 661import testNapi from 'libentry.so'; 662try { 663 let value = new Uint8Array([1, 2, 3, 4]); 664 let data = "123"; 665 hilog.info(0x0000, 'testTag', 'Test Node-API napi_is_typedarray: %{public}s', testNapi.isTypedarray(value)); 666 hilog.info(0x0000, 'testTag', 'Test Node-API napi_is_typedarray: %{public}s', testNapi.isTypedarray(data)); 667} catch (error) { 668 hilog.error(0x0000, 'testTag', 'Test Node-API napi_is_typedarray error: %{public}s', error.message); 669} 670``` 671<!-- @[ark_napi_is_typed_array](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 672 673### napi_get_typedarray_info 674 675获取给定TypedArray的各种属性。 676 677cpp部分代码 678 679```cpp 680#include "napi/native_api.h" 681 682static napi_value GetTypedarrayInfo(napi_env env, napi_callback_info info) 683{ 684 // 获取ArkTS侧传入的参数,第一个参数为需要获得的信息的TypedArray类型数据,第二个参数为需要获得的信息类型的枚举值 685 size_t argc = 2; 686 napi_value args[2] = {nullptr}; 687 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 688 // 将第二个参数转为int32类型便于比较 689 int32_t infoTypeParam; 690 napi_get_value_int32(env, args[1], &infoTypeParam); 691 // 定义枚举类型与ArkTS侧枚举类型InfoType顺序含义一致 692 enum InfoType { INFO_TYPE = 1, INFO_LENGTH, INFO_ARRAY_BUFFER, INFO_BYTE_OFFSET }; 693 void *data; 694 napi_typedarray_type type; 695 size_t byteOffset, length; 696 napi_value arraybuffer; 697 // 调用接口napi_get_typedarray_info获得TypedArray类型数据的信息 698 napi_get_typedarray_info(env, args[0], &type, &length, &data, &arraybuffer, &byteOffset); 699 napi_value result = nullptr; 700 // 根据属性名,返回TypedArray对应的属性值 701 switch (infoTypeParam) { 702 case INFO_TYPE: 703 // 如果传入的参数是int8类型的TypedArray数据,它的类型(type)为napi_int8_array 704 napi_value int8_type; 705 napi_get_boolean(env, type == napi_int8_array, &int8_type); 706 result = int8_type; 707 break; 708 case INFO_LENGTH: 709 // TypedArray中元素的字节长度 710 napi_value napiLength; 711 napi_create_int32(env, length, &napiLength); 712 result = napiLength; 713 break; 714 case INFO_BYTE_OFFSET: 715 // TypedArray数组的第一个元素所在的基础原生数组中的字节偏移量 716 napi_value napiByteOffset; 717 napi_create_int32(env, byteOffset, &napiByteOffset); 718 result = napiByteOffset; 719 break; 720 case INFO_ARRAY_BUFFER: 721 // TypedArray下的ArrayBuffer 722 result = arraybuffer; 723 break; 724 default: 725 napi_throw_error(env, nullptr, "infoType is not the InfoType"); 726 break; 727 } 728 return result; 729} 730``` 731<!-- @[napi_get_typed_array_info](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 732 733接口声明 734 735```ts 736// index.d.ts 737export const getTypedarrayInfo: <T>(typeArray: T, infoType: number) => ArrayBuffer | number | boolean; 738``` 739<!-- @[napi_get_typed_array_info_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 740 741ArkTS侧示例代码 742 743```ts 744import { hilog } from '@kit.PerformanceAnalysisKit'; 745import testNapi from 'libentry.so'; 746 747// 传入TypedArray类型数据。TypedArray是一种用来描述二进制数据的类数组数据视图,没有直接构造器,可以用其子类构造类数组 748// TypedArray的子类有: Int8Array Uint8Array Uint8ClampedArray Int16Array Int32Array等 749let int8Array = new Int8Array([15, 7]); 750// 定义枚举类型 这些都是TypedArray的属性 751enum InfoType { 752 TYPE = 1, // 传入的TypedArray的类型 753 LENGTH = 2, // 传入的TypedArray的长度 754 ARRAY_BUFFER = 3, // TypedArray下的ArrayBuffer 755 BYTE_OFFSET = 4 // 数组的第一个元素所在的基础原生数组中的字节偏移量 756}; 757try { 758 let arrbuff = testNapi.getTypedarrayInfo(int8Array, InfoType.ARRAY_BUFFER) as ArrayBuffer; 759 // 将arraybuffer转为数组 760 let arr = new Array(new Int8Array(arrbuff)); 761 hilog.info(0x0000, 'Node-API', 'get_typedarray_info_arraybuffer: %{public}s', arr.toString()); 762 hilog.info(0x0000, 'Node-API', 'get_typedarray_info_isIn8Array: %{public}s', testNapi.getTypedarrayInfo(int8Array, InfoType.TYPE).toString()); 763 hilog.info(0x0000, 'Node-API', 'get_typedarray_info_length: %{public}d', testNapi.getTypedarrayInfo(int8Array, InfoType.LENGTH)); 764 hilog.info(0x0000, 'Node-API', 'get_typedarray_info_byte_offset: %{public}d', testNapi.getTypedarrayInfo(int8Array, InfoType.BYTE_OFFSET)); 765} catch (error) { 766 hilog.error(0x0000, 'testTag', 'Test Node-API napi_get_typedarray_info error: %{public}s', error.message); 767} 768``` 769<!-- @[ark_napi_get_typed_array_info](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 770 771### napi_create_dataview 772 773创建dataview对象,便于访问和操作二进制数据,需要提供一个指向二进制数据的缓冲区,并指定要包含的字节数。 774 775cpp部分代码 776 777```cpp 778#include "napi/native_api.h" 779 780static napi_value CreateDataView(napi_env env, napi_callback_info info) 781{ 782 // 获取ArkTS侧传入的参数 783 size_t argc = 1; 784 napi_value args[1] = {nullptr}; 785 napi_value arraybuffer = nullptr; 786 napi_value result = nullptr; 787 // DataView的字节长度 788 size_t byteLength = 12; 789 // 字节偏移量 790 size_t byteOffset = 4; 791 // 获取回调函数的参数信息 792 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 793 // 将参数转换为对象类型 794 napi_coerce_to_object(env, args[0], &arraybuffer); 795 // 创建一个数据视图对象,并指定字节长度和字节偏移量 796 napi_status status = napi_create_dataview(env, byteLength, arraybuffer, byteOffset, &result); 797 if (status != napi_ok) { 798 // 抛出创建DataView内容失败的错误 799 napi_throw_error(env, nullptr, "Failed to create DataView"); 800 return nullptr; 801 } 802 // 获取DataView的指针和长度信息 803 uint8_t *data = nullptr; 804 size_t length = 0; 805 napi_get_dataview_info(env, result, &length, (void **)&data, nullptr, nullptr); 806 // 为DataView赋值 807 for (size_t i = 0; i < length; i++) { 808 data[i] = static_cast<uint8_t>(i + 1); 809 } 810 return result; 811} 812``` 813<!-- @[napi_create_data_view](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 814 815接口声明 816 817```ts 818// index.d.ts 819export const createDataView: (arraybuffer:ArrayBuffer) => DataView | undefined; 820``` 821<!-- @[napi_create_data_view_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 822 823ArkTS侧示例代码 824 825```ts 826import { hilog } from '@kit.PerformanceAnalysisKit'; 827import testNapi from 'libentry.so'; 828 829const arrayBuffer = new ArrayBuffer(16); 830const dataView = testNapi.createDataView(arrayBuffer) as DataView; 831hilog.info(0x0000, 'testTag', 'Test Node-API dataView:%{public}d', dataView.byteLength); 832hilog.info(0x0000, 'testTag', 'Test Node-API dataView第一个数据:%{public}d', dataView.getInt8(0)); 833``` 834<!-- @[ark_napi_create_data_view](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 835 836### napi_is_dataview 837 838用于在Node-API模块中判断ArkTS侧给定的napi_value是否为DataView。 839 840cpp部分代码 841 842```cpp 843#include "napi/native_api.h" 844 845static napi_value IsDataView(napi_env env, napi_callback_info info) 846{ 847 // 获取ArkTS侧传入的参数 848 size_t argc = 1; 849 napi_value args[1] = {nullptr}; 850 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 851 852 // 调用napi_is_dataview接口判断给定入参是否为DataView数据。 853 bool result; 854 napi_status status; 855 status = napi_is_dataview(env, args[0], &result); 856 if (status != napi_ok) { 857 napi_throw_error(env, nullptr, "Node-API napi_is_dataview fail"); 858 return nullptr; 859 } 860 // 将结果转成napi_value类型返回。 861 napi_value returnValue; 862 napi_get_boolean(env, result, &returnValue); 863 864 return returnValue; 865} 866``` 867<!-- @[napi_is_data_view](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 868 869接口声明 870 871```ts 872// index.d.ts 873export const isDataView: (date: DataView | string) => boolean | undefined; 874``` 875<!-- @[napi_is_data_view_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 876 877ArkTS侧示例代码 878 879```ts 880import { hilog } from '@kit.PerformanceAnalysisKit'; 881import testNapi from 'libentry.so'; 882try { 883 let buffer = new ArrayBuffer(16); 884 let dataView = new DataView(buffer); 885 let data = "123"; 886 hilog.info(0x0000, 'testTag', 'Test Node-API napi_is_dataview: %{public}s', testNapi.isDataView(dataView)); 887 hilog.info(0x0000, 'testTag', 'Test Node-API napi_is_dataview: %{public}s', testNapi.isDataView(data)); 888} catch (error) { 889 hilog.error(0x0000, 'testTag', 'Test Node-API napi_is_dataview error: %{public}s', error.message); 890} 891``` 892<!-- @[ark_napi_is_data_view](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 893 894### napi_get_dataview_info 895 896获取给定DataView的各种属性。 897 898cpp部分代码 899 900```cpp 901#include "napi/native_api.h" 902 903static napi_value GetDataViewInfo(napi_env env, napi_callback_info info) 904{ 905 // 获取ArkTS侧传入的参数 906 size_t argc = 2; 907 napi_value args[2] = {nullptr}; 908 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 909 // 将第二个参数转为int32类型的数字 910 int32_t infoType; 911 napi_get_value_int32(env, args[1], &infoType); 912 size_t byteLength; 913 void *data; 914 napi_value arrayBuffer; 915 size_t byteOffset; 916 // 定义枚举类型与ArkTS侧枚举类型InfoType顺序含义一致 917 enum InfoType { BYTE_LENGTH = 0, ARRAY_BUFFER, BYTE_OFFSET }; 918 // 获取dataview信息 919 napi_get_dataview_info(env, args[0], &byteLength, &data, &arrayBuffer, &byteOffset); 920 napi_value result = nullptr; 921 switch (infoType) { 922 case BYTE_LENGTH: 923 // 返回查询DataView的字节数 924 napi_value napiByteLength; 925 napi_create_int32(env, byteLength, &napiByteLength); 926 result = napiByteLength; 927 break; 928 case ARRAY_BUFFER: 929 // 返回查询DataView的arraybuffer 930 result = arrayBuffer; 931 break; 932 case BYTE_OFFSET: 933 // 返回查询DataView的偏移字节量 934 napi_value napiByteOffset; 935 napi_create_int32(env, byteOffset, &napiByteOffset); 936 result = napiByteOffset; 937 break; 938 default: 939 napi_throw_error(env, nullptr, "infoType is not the InfoType"); 940 break; 941 } 942 return result; 943} 944``` 945<!-- @[napi_get_data_view_info](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/napi_init.cpp) --> 946 947接口声明 948 949```ts 950// index.d.ts 951export const getDataViewInfo: (dataView: DataView, infoType: number) => ArrayBuffer | number; 952``` 953<!-- @[napi_get_data_view_info_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/cpp/types/libentry/Index.d.ts) --> 954 955ArkTS侧示例代码 956 957```ts 958import { hilog } from '@kit.PerformanceAnalysisKit'; 959import testNapi from 'libentry.so'; 960 961// 创建一个ArrayBuffer 962let arrayBuffer = new Int8Array([2, 5]).buffer; 963// 使用arrayBuffer创建一个dataView 964let dataView = new DataView(arrayBuffer); 965// 定义一个枚举类型 966enum InfoType { 967 BYTE_LENGTH = 0, 968 ARRAY_BUFFER = 1, 969 BYTE_OFFSET = 2, 970}; 971try { 972 // 传入DataView类型参数查询DataView的字节数 973 hilog.info(0x0000, 'Node-API', 'get_dataview_info_bytelength %{public}d', testNapi.getDataViewInfo(dataView, InfoType.BYTE_LENGTH)); 974 // 传入DataView类型参数查询DataView的ArrayBuffer 975 let arrbuff = testNapi.getDataViewInfo(dataView, InfoType.ARRAY_BUFFER) as ArrayBuffer; 976 // 将arraybuffer转为数组 977 let arr = Array.from(new Int8Array(arrbuff)); 978 hilog.info(0x0000, 'Node-API', 'get_dataview_info_arraybuffer %{public}s', arr.toString()); 979 // 传入DataView类型参数查询DataView开始投影的数据缓冲区中的字节偏移量 980 hilog.info(0x0000, 'Node-API', 'get_dataview_info_byteoffset %{public}d', testNapi.getDataViewInfo(dataView, InfoType.BYTE_OFFSET)); 981} catch (error) { 982 hilog.error(0x0000, 'testTag', 'Test Node-API napi_get_dataview_info error: %{public}s', error.message); 983} 984``` 985<!-- @[ark_napi_get_data_view_info](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIArray/entry/src/main/ets/pages/Index.ets) --> 986 987以上代码如果要在native cpp中打印日志,需在CMakeLists.txt文件中添加以下配置信息(并添加头文件:#include "hilog/log.h"): 988 989```text 990// CMakeLists.txt 991add_definitions( "-DLOG_DOMAIN=0xd0d0" ) 992add_definitions( "-DLOG_TAG=\"testTag\"" ) 993target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so) 994``` 995