1# 使用Node-API接口创建和获取string值 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的六个关于string的接口,可以实现Node-API模块与ArkTS字符串的交互。 12 13## 基本概念 14 15字符串是编程中常用的数据类型,用于存储和操作文本数据。它可以表示和处理字符序列,构建用户界面元素(如标签、按钮和文本框),处理用户输入,验证和格式化数据。不同编码支持的字符集和语言不同,以下是一些主要编码方案及其区别: 16 17- **ASCII**:ASCII是最早的字符编码方案之一,使用7位编码,只能表示英文字母、数字和一些基本符号。它是许多其他编码方案的基础。 18- **UTF-8**:UTF-8是一种变长编码方案,可以表示全球范围的字符集。它使用8位编码,根据字符的不同范围使用不同长度的字节序列。UTF-8是互联网上广泛使用的编码方案。 19- **UTF-16**:UTF-16是一种定长或变长编码方案,使用16位编码。它可以表示全球范围的字符集,并且适用于较大的字符集。 20- **ISO-8859-1(Latin-1)**:ISO-8859-1是一种单字节编码方案,使用8位编码。它主要用于表示拉丁字母字符集,包括欧洲大部分语言。 21 22## 场景和功能介绍 23 24以下Node-API接口主要用于string值的创建和获取,使用场景如下: 25 26| 接口 | 描述 | 27| -------- | -------- | 28| napi_get_value_string_utf8 | 需要将ArkTS的字符类型的数据转换为utf8编码的字符时使用这个函数。 | 29| napi_create_string_utf8 | 需要通过UTF8编码的C字符串创建ArkTS string值时使用这个函数。 | 30| napi_get_value_string_utf16 | 需要将ArkTS的字符类型的数据转换为utf16编码的字符时使用这个函数。 | 31| napi_create_string_utf16 | 需要通过UTF16编码的C字符串创建ArkTS string值时使用这个函数。 | 32| napi_get_value_string_latin1 | 需要将ArkTS的字符类型的数据转换为ISO-8859-1编码的字符时使用这个函数。 | 33| napi_create_string_latin1 | 需要通过ISO-8859-1编码的字符串创建ArkTS string值时使用这个函数。 | 34 35## 使用示例 36 37Node-API接口开发流程参考[使用Node-API实现跨语言交互开发流程](use-napi-process.md),本文仅对接口对应C++及ArkTS相关代码进行展示。 38 39### napi_get_value_string_utf8 40 41将ArkTS的字符类型的数据转换为UTF-8编码的字符。 42 43cpp部分代码 44 45```cpp 46#include "napi/native_api.h" 47#include "hilog/log.h" 48#include <cstring> 49 50static napi_value GetValueStringUtf8(napi_env env, napi_callback_info info) 51{ 52 size_t argc = 1; 53 napi_value args[1] = {nullptr}; 54 55 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 56 // 获取字符串的长度 57 size_t length = 0; 58 napi_status status = napi_get_value_string_utf8(env, args[0], nullptr, 0, &length); 59 // 传入一个非字符串 napi_get_value_string_utf8接口会返回napi_string_expected 60 if (status != napi_ok) { 61 OH_LOG_ERROR(LOG_APP, "napi_get_value_string_utf8 failed"); 62 return nullptr; 63 } 64 char* buf = new char[length + 1]; 65 std::memset(buf, 0, length + 1); 66 status = napi_get_value_string_utf8(env, args[0], buf, length + 1, &length); 67 if (status != napi_ok) { 68 if (buf) { 69 delete[] buf; 70 } 71 OH_LOG_ERROR(LOG_APP, "napi_get_value_string_utf8 failed"); 72 return nullptr; 73 } 74 napi_value result = nullptr; 75 status = napi_create_string_utf8(env, buf, length, &result); 76 if (buf) { 77 delete[] buf; 78 } 79 if (status != napi_ok) { 80 napi_throw_error(env, nullptr, "napi_create_string_utf8 failed"); 81 return nullptr; 82 } 83 return result; 84} 85``` 86<!-- @[napi_get_value_string_utf8](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/napi_init.cpp) --> 87 88接口声明 89 90```ts 91// index.d.ts 92export const getValueStringUtf8: (param: string | number) => string | undefined; 93``` 94<!-- @[napi_get_value_string_utf8_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/types/libentry/Index.d.ts) --> 95 96ArkTS侧示例代码 97 98```ts 99import { hilog } from '@kit.PerformanceAnalysisKit'; 100import testNapi from 'libentry.so'; 101// 分别传入字符和非字符检测接口,传入字符串类型的数据将返回原字符串,传入其他类型返回undefined 102hilog.info(0x0000, 'testTag', 'Test Node-API get_value_string_utf8_string %{public}s', testNapi.getValueStringUtf8('aaBC+-$%^你好123')); 103hilog.info(0x0000, 'testTag', 'Test Node-API get_value_string_utf8_not_string %{public}s', testNapi.getValueStringUtf8(50)); 104``` 105<!-- @[ark_napi_get_value_string_utf8](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/ets/pages/Index.ets) --> 106 107### napi_create_string_utf8 108 109用于创建一个UTF-8编码的ArkTS字符串。 110 111cpp部分代码 112 113```cpp 114#include "napi/native_api.h" 115#include <string> 116 117static napi_value CreateStringUtf8(napi_env env, napi_callback_info info) 118{ 119 const char *str = u8"你好, World!, successes to create UTF-8 string! 111"; 120 size_t length = strlen(str); 121 napi_value result = nullptr; 122 napi_status status = napi_create_string_utf8(env, str, length, &result); 123 if (status != napi_ok) { 124 napi_throw_error(env, nullptr, "Failed to create UTF-8 string"); 125 return nullptr; 126 } 127 return result; 128} 129``` 130<!-- @[napi_create_string_utf8](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/napi_init.cpp) --> 131 132接口声明 133 134```ts 135// index.d.ts 136export const createStringUtf8: () => string | undefined; 137``` 138<!-- @[napi_create_string_utf8_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/types/libentry/Index.d.ts) --> 139 140ArkTS侧示例代码 141 142```ts 143import { hilog } from '@kit.PerformanceAnalysisKit'; 144import testNapi from 'libentry.so'; 145 146hilog.info(0x0000, 'testTag', 'Test Node-API napi_create_string_utf8:%{public}s', testNapi.createStringUtf8()); 147``` 148<!-- @[ark_napi_create_string_utf8](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/ets/pages/Index.ets) --> 149 150### napi_get_value_string_utf16 151 152将ArkTS的字符类型的数据转换为UTF-16编码的字符。 153 154cpp部分代码 155 156```cpp 157#include "napi/native_api.h" 158 159// 定义字符串缓冲区的最大长度 160static const int MAX_BUFFER_SIZE = 128; 161 162static napi_value GetValueStringUtf16(napi_env env, napi_callback_info info) 163{ 164 size_t argc = 1; 165 napi_value args[1]; 166 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 167 napi_value result = nullptr; 168 // 字符串的缓冲区 169 char16_t buffer[MAX_BUFFER_SIZE]; 170 // 字符串的缓冲区大小 171 size_t bufferSize = MAX_BUFFER_SIZE; 172 // 字符串的长度 173 size_t stringLen; 174 // 获取字符串的数据和长度 175 napi_get_value_string_utf16(env, args[0], buffer, bufferSize, &stringLen); 176 // 获取字符串返回结果 177 napi_create_string_utf16(env, buffer, stringLen, &result); 178 // 返回结果 179 return result; 180} 181``` 182<!-- @[napi_get_value_string_utf16](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/napi_init.cpp) --> 183 184接口声明 185 186```ts 187// index.d.ts 188export const getValueStringUtf16: (data: string) => string; 189``` 190<!-- @[napi_get_value_string_utf16_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/types/libentry/Index.d.ts) --> 191 192ArkTS侧示例代码 193 194```ts 195import { hilog } from '@kit.PerformanceAnalysisKit'; 196import testNapi from 'libentry.so'; 197 198let result = testNapi.getValueStringUtf16('hello,'); 199hilog.info(0x0000,'testTag','Node-API napi_get_value_string_utf16:%{public}s', result); 200``` 201<!-- @[ark_napi_get_value_string_utf16](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/ets/pages/Index.ets) --> 202 203### napi_create_string_utf16 204 205创建一个UTF-16编码的ArkTS字符串。 206 207cpp部分代码 208 209```cpp 210#include "napi/native_api.h" 211 212static napi_value CreateStringUtf16(napi_env env, napi_callback_info info) 213{ 214 const char16_t *str = u"你好, World!, successes to create UTF-16 string! 111"; 215 size_t length = NAPI_AUTO_LENGTH; 216 napi_value result = nullptr; 217 napi_status status = napi_create_string_utf16(env, str, length, &result); 218 if (status != napi_ok) { 219 napi_throw_error(env, nullptr, "Failed to create UTF-16 string"); 220 return nullptr; 221 } 222 return result; 223} 224``` 225<!-- @[napi_create_string_utf16](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/napi_init.cpp) --> 226 227接口声明 228 229```ts 230// index.d.ts 231export const createStringUtf16: () => string | undefined; 232``` 233<!-- @[napi_create_string_utf16_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/types/libentry/Index.d.ts) --> 234 235ArkTS侧示例代码 236 237```ts 238import { hilog } from '@kit.PerformanceAnalysisKit'; 239import testNapi from 'libentry.so'; 240 241hilog.info(0x0000, 'testTag', 'Test Node-API napi_create_string_utf16:%{public}s ', testNapi.createStringUtf16()); 242``` 243<!-- @[ark_napi_create_string_utf16](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/ets/pages/Index.ets) --> 244 245### napi_get_value_string_latin1 246 247将ArkTS的字符类型数据转换为ISO-8859-1编码。 248 249cpp部分代码 250 251```cpp 252#include "napi/native_api.h" 253 254static const int MAX_BUFFER_SIZE = 128; 255 256static napi_value GetValueStringLatin1(napi_env env, napi_callback_info info) 257{ 258 size_t argc = 1; 259 napi_value args[1] = {nullptr}; 260 napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); 261 char buf[MAX_BUFFER_SIZE]; 262 size_t length = 0; 263 napi_value napi_Res = nullptr; 264 napi_status status = napi_get_value_string_latin1(env, args[0], buf, MAX_BUFFER_SIZE, &length); 265 // 当输入的值不是字符串时,接口会返回napi_string_expected 266 if (status != napi_ok) { 267 return nullptr; 268 } 269 napi_create_string_latin1(env, buf, length, &napi_Res); 270 return napi_Res; 271} 272``` 273<!-- @[napi_get_value_string_latin1](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/napi_init.cpp) --> 274 275接口声明 276 277```ts 278// index.d.ts 279export const getValueStringLatin1: (param: number | string) => string | undefined; 280``` 281<!-- @[napi_get_value_string_latin1_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/types/libentry/Index.d.ts) --> 282 283ArkTS侧示例代码 284 285```ts 286import { hilog } from '@kit.PerformanceAnalysisKit'; 287import testNapi from 'libentry.so'; 288// 传入非字符型数据,函数返回undefined 289hilog.info(0x0000, 'testTag', 'Test Node-API get_value_string_latin1_not_string %{public}s', testNapi.getValueStringLatin1(10)); 290// ISO-8859-1编码不支持中文,传入中文字符会乱码 291hilog.info(0x0000, 'testTag', 'Test Node-API get_value_string_latin1_string_chinese %{public}s', testNapi.getValueStringLatin1('中文')); 292// 传入其他字符,不会乱码 293hilog.info(0x0000, 'testTag', 'Test Node-API get_value_string_latin1_string %{public}s', testNapi.getValueStringLatin1('abo ABP=-&*/')); 294``` 295<!-- @[ark_napi_get_value_string_latin1](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/ets/pages/Index.ets) --> 296 297### napi_create_string_latin1 298 299创建一个Latin1编码的ArkTS字符串。 300 301cpp部分代码 302 303```cpp 304#include "napi/native_api.h" 305 306static napi_value CreateStringLatin1(napi_env env, napi_callback_info info) 307{ 308 const char *str = "Hello, World! éçñ, successes to create Latin1 string! 111"; 309 size_t length = NAPI_AUTO_LENGTH; 310 napi_value result = nullptr; 311 napi_status status = napi_create_string_latin1(env, str, length, &result); 312 if (status != napi_ok) { 313 // 处理错误 314 napi_throw_error(env, nullptr, "Failed to create Latin1 string"); 315 return nullptr; 316 } 317 return result; 318} 319``` 320<!-- @[napi_create_string_latin1](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/napi_init.cpp) --> 321 322接口声明 323 324```ts 325// index.d.ts 326export const createStringLatin1: () => string | undefined; 327``` 328<!-- @[napi_create_string_latin1_api](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/cpp/types/libentry/Index.d.ts) --> 329 330ArkTS侧示例代码 331 332```ts 333import { hilog } from '@kit.PerformanceAnalysisKit'; 334import testNapi from 'libentry.so'; 335 336hilog.info(0x0000, 'testTag', 'Test Node-API napi_create_string_latin1:%{public}s', testNapi.createStringLatin1()); 337``` 338<!-- @[ark_napi_create_string_latin1](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIUse/NodeAPIString/entry/src/main/ets/pages/Index.ets) --> 339 340以上代码如果要在native cpp中打印日志,需在CMakeLists.txt文件中添加以下配置信息(并添加头文件:#include "hilog/log.h"): 341 342```text 343// CMakeLists.txt 344add_definitions( "-DLOG_DOMAIN=0xd0d0" ) 345add_definitions( "-DLOG_TAG=\"testTag\"" ) 346target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so) 347``` 348