1# Creating and Obtaining String Values Using JSVM-API
2
3## Introduction
4
5This topic walks you through on how to use JSVM-API to convert data between native strings and JavaScript (JS) strings.
6
7## Basic Concepts
8
9As the common data type in programming, string is a sequence of characters used to represent text. It can also be used to build user interface (UI) elements such as labels, buttons, and text boxes, process user input, and validate and format input data. Different encodings support different character sets and languages. Major encoding schemes include the following:
10
11- ASCII<br>ASCII is one of the earliest character encoding schemes. It uses 7 bits to represent English letters, digits, and some basic symbols. It serves as the foundation for encoding schemes.
12- UTF-8<br>UTF-8 is a variable-length encoding scheme that can represent any Unicode character. It uses 8 bits per character and uses byte sequences of different lengths depending on the range of the character. UTF-8 is widely used for web content.
13- UTF-16<br>UTF-16 is a fixed-length or variable-length encoding scheme that uses 16 bits per character. It can represent all Unicode characters and is suitable for larger character sets.
14- ISO-8859-1 (Latin-1)<br>ISO-8859-1 is a single-byte coding scheme that uses 8 bits per character. It is mainly used to represent Latin alphabet characters and commonly used in European languages.
15
16## Available APIs
17
18| API                      | Description                      |
19|----------------------------|--------------------------------|
20| OH_JSVM_GetValueStringUtf8       | Obtains the UTF8-encoded string from a JS string.|
21| OH_JSVM_CreateStringUtf8          | Creates a JS string object from a UTF8-encoded C string.|
22| OH_JSVM_GetValueStringUtf16      | Obtains the UTF16-encoded string from a JS string.|
23| OH_JSVM_CreateStringUtf16         | Creates a JS string from a UTF16-encoded C string.|
24| OH_JSVM_GetValueStringLatin1     | Obtains the ISO-8859-1-encoded string from a JS string.|
25| OH_JSVM_CreateStringLatin1        | Creates a JS string object from an ISO-8859-1-encoded C string. ISO-8859-1 is also referred to as Latin-1.|
26
27## Example
28
29If you are just starting out with JSVM-API, see [JSVM-API Development Process](use-jsvm-process.md). The following demonstrates only the C++ code involved in string management.
30
31### OH_JSVM_GetValueStringUtf8
32
33Use **OH_JSVM_GetValueStringUtf8** to convert a JS string into a UTF-8-encoded string.
34
35CPP code:
36
37```cpp
38// hello.cpp
39#include "napi/native_api.h"
40#include "ark_runtime/jsvm.h"
41#include <hilog/log.h>
42#include <cstdlib>
43// Define OH_JSVM_GetValueStringUtf8.
44static JSVM_Value GetValueStringUtf8(JSVM_Env env, JSVM_CallbackInfo info)
45{
46    size_t argc = 1;
47    JSVM_Value args[1] = {nullptr};
48    OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr);
49    size_t length = 0;
50    JSVM_Status status = OH_JSVM_GetValueStringUtf8(env, args[0], nullptr, 0, &length);
51    char *buf = (char *)malloc(length + 1);
52    status = OH_JSVM_GetValueStringUtf8(env, args[0], buf, length + 1, &length);
53    if (status != JSVM_OK) {
54        OH_LOG_ERROR(LOG_APP, "JSVM GetValueStringUtf8 fail");
55        return nullptr;
56    } else {
57        OH_LOG_INFO(LOG_APP, "JSVM GetValueStringUtf8 success: %{public}s", buf);
58    }
59    JSVM_Value result = nullptr;
60    OH_JSVM_CreateStringUtf8(env, buf, length, &result);
61    return result;
62}
63// Register the GetValueStringUtf8 callback.
64static JSVM_CallbackStruct param[] = {
65    {.data = nullptr, .callback = GetValueStringUtf8},
66};
67static JSVM_CallbackStruct *method = param;
68// Set a property descriptor named getValueStringUtf8 and associate it with a callback. This allows the GetValueStringUtf8 callback to be called from JS.
69static JSVM_PropertyDescriptor descriptor[] = {
70    {"getValueStringUtf8", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
71};
72
73// Call the C++ code from JS.
74const char *srcCallNative = R"JS(
75    let data = "aaBC+-$%^Hello 123";
76    let script = getValueStringUtf8(data);
77)JS";
78```
79
80**Expected output**
81
82```ts
83JSVM GetValueStringUtf8 success: aaBC+-$%^Hello 123
84```
85
86**NOTE**<br>The call fails if the input parameter **arg** of **getValueStringUtf8()** is not of the string type.
87
88### OH_JSVM_CreateStringUtf8
89
90Use **OH_JSVM_CreateStringUtf8** to create a JS string from a UTF8-encoded C string.
91
92CPP code:
93
94```cpp
95// hello.cpp
96#include "napi/native_api.h"
97#include "ark_runtime/jsvm.h"
98#include <hilog/log.h>
99#include <string>
100// Define OH_JSVM_CreateStringUtf8.
101static JSVM_Value CreateStringUtf8(JSVM_Env env, JSVM_CallbackInfo info)
102{
103    const char *str = u8"Hello, World!, successes to create UTF-8 string!";
104    size_t length = strlen(str);
105    JSVM_Value result = nullptr;
106    JSVM_Status status = OH_JSVM_CreateStringUtf8(env, str, length, &result);
107    if (status != JSVM_OK) {
108        OH_JSVM_ThrowError(env, nullptr, "Failed to create UTF-8 string");
109        return nullptr;
110    } else {
111        OH_LOG_INFO(LOG_APP, "JSVM CreateStringUtf8 success: %{public}s", str);
112    }
113    return result;
114}
115// Register the CreateStringUtf8 callback.
116static JSVM_CallbackStruct param[] = {
117    {.data = nullptr, .callback = CreateStringUtf8},
118};
119static JSVM_CallbackStruct *method = param;
120// Set a property descriptor named createStringUtf8 and associate it with a callback. This allows the CreateStringUtf8 callback to be called from JS.
121static JSVM_PropertyDescriptor descriptor[] = {
122    {"createStringUtf8", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
123};
124
125// Call the C++ code from JS.
126const char *srcCallNative = R"JS(
127    let script = createStringUtf8();
128)JS";
129```
130
131**Expected output**
132
133
134```ts
135JSVM CreateStringUtf8 success: Hello, World!, successes to create UTF-8 string!
136```
137
138### OH_JSVM_GetValueStringUtf16
139
140Use **OH_JSVM_GetValueStringUtf16** to convert a JS string into a UTF-16-encoded string.
141
142CPP code:
143
144```cpp
145// hello.cpp
146#include "napi/native_api.h"
147#include "ark_runtime/jsvm.h"
148#include <hilog/log.h>
149#include <codecvt>
150#include <locale>
151#include <cstdlib>
152
153// Define OH_JSVM_GetValueStringUtf16.
154// Set the maximum length of the string buffer.
155static const int MAX_BUFFER_SIZE = 128;
156static JSVM_Value GetValueStringUtf16(JSVM_Env env, JSVM_CallbackInfo info) {
157    size_t argc = 1;
158    JSVM_Value args[1] = {nullptr};
159    OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr);
160    JSVM_Value result = nullptr;
161    size_t length = 0;
162    char16_t buffer[MAX_BUFFER_SIZE] = {0};
163    // Size of the buffer for storing the string.
164    size_t bufferSize = MAX_BUFFER_SIZE;
165    JSVM_Status status = OH_JSVM_GetValueStringUtf16(env, args[0], buffer, bufferSize, &length);
166    // Convert char16_t to std::u16string.
167    std::u16string u16str = {buffer};
168    // Convert std::u16string to std::string.
169    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter;
170    std::string str = converter.to_bytes(u16str);
171    // Obtain the string.
172    if (status != JSVM_OK) {
173        OH_LOG_ERROR(LOG_APP, "JSVM GetValueStringUtf16 fail");
174        return nullptr;
175    } else {
176        OH_LOG_INFO(LOG_APP, "JSVM GetValueStringUtf16 success: %{public}s", str.c_str());
177    }
178    return result;
179}
180// Register the GetValueStringUtf16 callback.
181static JSVM_CallbackStruct param[] = {
182    {.data = nullptr, .callback = GetValueStringUtf16},
183};
184static JSVM_CallbackStruct *method = param;
185// Set a property descriptor named getValueStringUtf16 and associate it with a callback. This allows the GetValueStringUtf16 callback to be called from JS.
186static JSVM_PropertyDescriptor descriptor[] = {
187    {"getValueStringUtf16", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
188};
189
190// Call the C++ code from JS.
191const char *srcCallNative = R"JS(
192    let data = "ahello.";
193    let script = getValueStringUtf16(data);
194)JS";
195```
196
197**Expected output**
198
199```ts
200JSVM GetValueStringUtf16 success: ahello.
201```
202
203**NOTE**<br>The call fails if the input parameter **arg** of **getValueStringUtf16()** is not of the string type.
204
205### OH_JSVM_CreateStringUtf16
206
207Use **OH_JSVM_GetValueStringUtf16** to create a JS string from a UTF16-encoded C string.
208
209CPP code:
210
211```cpp
212// hello.cpp
213#include "napi/native_api.h"
214#include "ark_runtime/jsvm.h"
215#include <hilog/log.h>
216#include <codecvt>
217#include <locale>
218#include <cstring>
219
220// Define OH_JSVM_CreateStringUtf16.
221static JSVM_Value CreateStringUtf16(JSVM_Env env, JSVM_CallbackInfo info)
222{
223    const char16_t *str = u"Hello, World!, successes to create UTF-16 string!";
224    std::u16string ustr(str);
225    size_t length = ustr.length();
226    JSVM_Value result = nullptr;
227    JSVM_Status status = OH_JSVM_CreateStringUtf16(env, str, length, &result);
228    std::u16string u16str = {str};
229    // Convert std::u16string to std::string.
230    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter;
231    std::string strResult = converter.to_bytes(u16str);
232    if (status != JSVM_OK) {
233        OH_LOG_ERROR(LOG_APP, "JSVM CreateStringUtf16 fail");
234    }else {
235        OH_LOG_INFO(LOG_APP, "JSVM CreateStringUtf16 success: %{public}s", strResult.c_str());
236    }
237    return result;
238}
239// Register the CreateStringUtf16 callback.
240static JSVM_CallbackStruct param[] = {
241    {.data = nullptr, .callback = CreateStringUtf16},
242};
243static JSVM_CallbackStruct *method = param;
244// Set a property descriptor named createStringUtf16 and associate it with a callback. This allows the CreateStringUtf16 callback to be called from JS.
245static JSVM_PropertyDescriptor descriptor[] = {
246    {"createStringUtf16", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
247};
248
249// Call the C++ code from JS.
250const char *srcCallNative = R"JS(
251    let script = createStringUtf16();
252)JS";
253```
254
255**Expected output**
256
257```ts
258JSVM CreateStringUtf16 success: Hello, World!, successes to create UTF-16 string!
259```
260
261### OH_JSVM_GetValueStringLatin1
262
263Use **OH_JSVM_GetValueStringLatin1** to convert a JS string into an ISO-8859-1-encoded string.
264
265CPP code:
266
267```cpp
268// hello.cpp
269#include "napi/native_api.h"
270#include "ark_runtime/jsvm.h"
271#include <hilog/log.h>
272#include <cstdlib>
273// Define OH_JSVM_GetValueStringLatin1.
274// Set the maximum length of the string buffer.
275static const int MAX_BUFFER_SIZE = 128;
276static JSVM_Value GetValueStringLatin1(JSVM_Env env, JSVM_CallbackInfo info)
277{
278    size_t argc = 1;
279    JSVM_Value args[1] = {nullptr};
280    OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr);
281    char buf[MAX_BUFFER_SIZE];
282    size_t length;
283    JSVM_Value jsvmRes = nullptr;
284    JSVM_Status status = OH_JSVM_GetValueStringLatin1(env, args[0], buf, MAX_BUFFER_SIZE, &length);
285    if (status != JSVM_OK) {
286        OH_LOG_ERROR(LOG_APP, "JSVM GetValueStringLatin1 fail");
287    } else {
288        OH_LOG_INFO(LOG_APP, "JSVM GetValueStringLatin1 success: %{public}s", buf);
289    }
290    OH_JSVM_CreateStringLatin1(env, buf, length, &jsvmRes);
291    return jsvmRes;
292}
293// Register the GetValueStringLatin1 callback.
294static JSVM_CallbackStruct param[] = {
295    {.data = nullptr, .callback = GetValueStringLatin1},
296};
297static JSVM_CallbackStruct *method = param;
298// Set a property descriptor named getValueStringLatin1 and associate it with a callback. This allows the GetValueStringLatin1 callback to be called from JS.
299static JSVM_PropertyDescriptor descriptor[] = {
300    {"getValueStringLatin1", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
301};
302
303// Call the C++ code from JS.
304const char *srcCallNative = R"JS(
305    let data = "中文";
306    let script = getValueStringLatin1(data);
307)JS";
308```
309
310**Expected output**
311
312```ts
313// The ISO-8859-1 encoding does not support Chinese characters. If Chinese characters are passed in, garbled characters will be displayed.
314JSVM GetValueStringLatin1 success: -
315```
316
317**NOTE**<br>The call fails if the input parameter **arg** of **getValueStringLatin1()** is not of the string type.
318
319### OH_JSVM_CreateStringLatin1
320
321Use **OH_JSVM_CreateStringLatin1** to create a JS string from an ISO-8859-1-encoded C string.
322
323CPP code:
324
325```cpp
326// hello.cpp
327#include "napi/native_api.h"
328#include "ark_runtime/jsvm.h"
329#include <hilog/log.h>
330#include <cstring>
331// Register the CreateStringLatin1 callback.
332// Set the maximum length of the string buffer.
333static const int MAX_BUFFER_SIZE = 128;
334// Define OH_JSVM_CreateStringLatin1.
335static JSVM_Value CreateStringLatin1(JSVM_Env env, JSVM_CallbackInfo info)
336{
337    const char *str = "Hello, World! éçñ, successes to create Latin1 string!";
338    size_t length = JSVM_AUTO_LENGTH;
339    JSVM_Value result = nullptr;
340    JSVM_Status status = OH_JSVM_CreateStringLatin1(env, str, length, &result);
341    if (status != JSVM_OK) {
342        OH_LOG_ERROR(LOG_APP, "JSVM CreateStringLatin1 fail");
343    } else {
344        char buf[MAX_BUFFER_SIZE];
345        size_t length;
346        OH_JSVM_GetValueStringLatin1(env, result, buf, MAX_BUFFER_SIZE, &length);
347        OH_LOG_INFO(LOG_APP, "JSVM CreateStringLatin1 success: %{public}s", buf);
348    }
349    return result;
350}
351static JSVM_CallbackStruct param[] = {
352    {.data = nullptr, .callback = CreateStringLatin1},
353};
354static JSVM_CallbackStruct *method = param;
355// Set a property descriptor named createStringLatin1 and associate it with a callback. This allows the CreateStringLatin1 callback to be called from JS.
356static JSVM_PropertyDescriptor descriptor[] = {
357    {"createStringLatin1", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
358};
359
360// Call the C++ code from JS.
361const char *srcCallNative = R"JS(
362    let script = createStringLatin1();
363)JS";
364```
365
366**Expected output**
367
368```ts
369JSVM CreateStringLatin1 success: Hello, World! éçñ, successes to create Latin1 string!
370```
371<!--no_check-->