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