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++ and ArkTS code involved in string-related APIs. 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// Register the GetValueStringUtf8 callback. 43static JSVM_CallbackStruct param[] = { 44 {.data = nullptr, .callback = GetValueStringUtf8}, 45}; 46static JSVM_CallbackStruct *method = param; 47// Set a property descriptor named getValueStringUtf8 and associate it with a callback. This allows the GetValueStringUtf8 callback to be called from JS. 48static JSVM_PropertyDescriptor descriptor[] = { 49 {"getValueStringUtf8", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 50}; 51// Define OH_JSVM_GetValueStringUtf8. 52static JSVM_Value GetValueStringUtf8(JSVM_Env env, JSVM_CallbackInfo info) 53{ 54 size_t argc = 1; 55 JSVM_Value args[1] = {nullptr}; 56 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 57 size_t length = 0; 58 JSVM_Status status = OH_JSVM_GetValueStringUtf8(env, args[0], nullptr, 0, &length); 59 char *buf = (char *)malloc(length + 1); 60 status = OH_JSVM_GetValueStringUtf8(env, args[0], buf, length + 1, &length); 61 if (status != JSVM_OK) { 62 OH_LOG_ERROR(LOG_APP, "JSVM GetValueStringUtf8 fail"); 63 return nullptr; 64 } else { 65 OH_LOG_INFO(LOG_APP, "JSVM GetValueStringUtf8 success: %{public}s", buf); 66 } 67 JSVM_Value result = nullptr; 68 OH_JSVM_CreateStringUtf8(env, buf, length, &result); 69 return result; 70} 71``` 72 73ArkTS code: 74 75```ts 76import hilog from "@ohos.hilog" 77// Import the native APIs. 78import napitest from "libentry.so" 79try { 80 let data = `"aaBC+-$ %^Hello 123"`; 81 let script: string = `getValueStringUtf8(${data})`; 82 hilog.info(0x0000, 'testJSVM', 'Test JSVM getValueStringUtf8: %{public}s', napitest.runJsVm(script)); 83} catch (error) { 84 hilog.error(0x0000, 'testJSVM', 'Test JSVM getValueStringUtf8 error: %{public}s', error.message); 85} 86try { 87 let script: string = `getValueStringUtf8(50)`; 88 hilog.info(0x0000, 'testJSVM', 'Test JSVM getValueStringUtf8: %{public}s', napitest.runJsVm(script)); 89} catch (error) { 90 hilog.error(0x0000, 'testJSVM', 'Test JSVM getValueStringUtf8 error: %{public}s', error.message); 91} 92``` 93 94### OH_JSVM_CreateStringUtf8 95 96Use **OH_JSVM_CreateStringUtf8** to create a JS string from a UTF8-encoded C string. 97 98CPP code: 99 100```cpp 101// hello.cpp 102#include "napi/native_api.h" 103#include "ark_runtime/jsvm.h" 104#include <hilog/log.h> 105// Register the CreateStringUtf8 callback. 106static JSVM_CallbackStruct param[] = { 107 {.data = nullptr, .callback = CreateStringUtf8}, 108}; 109static JSVM_CallbackStruct *method = param; 110// Set a property descriptor named createStringUtf8 and associate it with a callback. This allows the CreateStringUtf8 callback to be called from JS. 111static JSVM_PropertyDescriptor descriptor[] = { 112 {"createStringUtf8", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 113}; 114// Define OH_JSVM_CreateStringUtf8. 115static JSVM_Value CreateStringUtf8(JSVM_Env env, JSVM_CallbackInfo info) 116{ 117 const char *str = u8"Hello, World!, successes to create UTF-8 string!"; 118 size_t length = strlen(str); 119 JSVM_Value result = nullptr; 120 JSVM_Status status = OH_JSVM_CreateStringUtf8(env, str, length, &result); 121 if (status != JSVM_OK) { 122 OH_JSVM_ThrowError(env, nullptr, "Failed to create UTF-8 string"); 123 return nullptr; 124 } else { 125 OH_LOG_INFO(LOG_APP, "JSVM CreateStringUtf8 success: %{public}s", str); 126 } 127 return result; 128} 129``` 130 131ArkTS code: 132 133```ts 134import hilog from "@ohos.hilog" 135// Import the native APIs. 136import napitest from "libentry.so" 137try { 138 let script: string = `createStringUtf8()`; 139 hilog.info(0x0000, 'testJSVM', 'Test JSVM createStringUtf8: %{public}s', napitest.runJsVm(script)); 140} catch (error) { 141 hilog.error(0x0000, 'testJSVM', 'Test JSVM createStringUtf8 error: %{public}s', error.message); 142} 143``` 144 145### OH_JSVM_GetValueStringUtf16 146 147Use **OH_JSVM_GetValueStringUtf16** to convert a JS string into a UTF-16-encoded string. 148 149CPP code: 150 151```cpp 152// hello.cpp 153#include "napi/native_api.h" 154#include "ark_runtime/jsvm.h" 155#include <hilog/log.h> 156#include <codecvt> 157#include <locale> 158 159// Register the GetValueStringUtf16 callback. 160static JSVM_CallbackStruct param[] = { 161 {.data = nullptr, .callback = GetValueStringUtf16}, 162}; 163static JSVM_CallbackStruct *method = param; 164// Set a property descriptor named getValueStringUtf16 and associate it with a callback. This allows the GetValueStringUtf16 callback to be called from JS. 165static JSVM_PropertyDescriptor descriptor[] = { 166 {"getValueStringUtf16", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 167}; 168// Define OH_JSVM_GetValueStringUtf16. 169// Set the maximum length of the string buffer. 170static const int MAX_BUFFER_SIZE = 128; 171static JSVM_Value GetValueStringUtf16(JSVM_Env env, JSVM_CallbackInfo info) { 172 size_t argc = 1; 173 JSVM_Value args[1] = {nullptr}; 174 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 175 JSVM_Value result = nullptr; 176 size_t length = 0; 177 char16_t buffer[MAX_BUFFER_SIZE] = {0}; 178 // Size of the buffer for storing the string. 179 size_t bufferSize = MAX_BUFFER_SIZE; 180 JSVM_Status status = OH_JSVM_GetValueStringUtf16(env, args[0], buffer, bufferSize, &length); 181 // Convert char16_t to std::u16string. 182 std::u16string u16str = {buffer}; 183 // Convert std::u16string to std::string. 184 std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter; 185 std::string str = converter.to_bytes(u16str); 186 // Obtain the string. 187 if (status != JSVM_OK) { 188 OH_LOG_ERROR(LOG_APP, "JSVM GetValueStringUtf16 fail"); 189 return nullptr; 190 } else { 191 OH_LOG_INFO(LOG_APP, "JSVM GetValueStringUtf16 success: %{public}s", str.c_str()); 192 } 193 return result; 194} 195``` 196 197ArkTS code: 198 199```ts 200import hilog from "@ohos.hilog" 201// Import the native APIs. 202import napitest from "libentry.so" 203try { 204 let data = `"ahello. "`; 205 let script: string = `getValueStringUtf16(${data})`; 206 hilog.info(0x0000, 'testJSVM', 'Test JSVM getValueStringUtf16: %{public}s', napitest.runJsVm(script)); 207} catch (error) { 208 hilog.error(0x0000, 'testJSVM', 'Test JSVM getValueStringUtf16 error: %{public}s', error.message); 209} 210try { 211 let script: string = `getValueStringUtf16(50)`; 212 hilog.info(0x0000, 'testJSVM', 'Test JSVM getValueStringUtf16: %{public}s', napitest.runJsVm(script)); 213} catch (error) { 214 hilog.error(0x0000, 'testJSVM', 'Test JSVM getValueStringUtf16 error: %{public}s', error.message); 215} 216``` 217 218### OH_JSVM_CreateStringUtf16 219 220Use **OH_JSVM_GetValueStringUtf16** to create a JS string from a UTF16-encoded C string. 221 222CPP code: 223 224```cpp 225// hello.cpp 226#include "napi/native_api.h" 227#include "ark_runtime/jsvm.h" 228#include <hilog/log.h> 229#include <codecvt> 230#include <locale> 231 232// Register the CreateStringUtf16 callback. 233static JSVM_CallbackStruct param[] = { 234 {.data = nullptr, .callback = CreateStringUtf16}, 235}; 236static JSVM_CallbackStruct *method = param; 237// Set a property descriptor named createStringUtf16 and associate it with a callback. This allows the CreateStringUtf16 callback to be called from JS. 238static JSVM_PropertyDescriptor descriptor[] = { 239 {"createStringUtf16", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 240}; 241// Define OH_JSVM_CreateStringUtf16. 242static JSVM_Value CreateStringUtf16(JSVM_Env env, JSVM_CallbackInfo info) 243{ 244 const char16_t *str = u"Hello, World!, successes to create UTF-16 string!"; 245 std::u16string ustr(str); 246 size_t length = ustr.length(); 247 JSVM_Value result = nullptr; 248 JSVM_Status status = OH_JSVM_CreateStringUtf16(env, str, length, &result); 249 std::u16string u16str = {str}; 250 // Convert std::u16string to std::string. 251 std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter; 252 std::string strResult = converter.to_bytes(u16str); 253 if (status != JSVM_OK) { 254 OH_LOG_ERROR(LOG_APP, "JSVM CreateStringUtf16 fail"); 255 }else { 256 OH_LOG_INFO(LOG_APP, "JSVM CreateStringUtf16 success: %{public}s", strResult.c_str()); 257 } 258 return result; 259} 260``` 261 262ArkTS code: 263 264```ts 265import hilog from "@ohos.hilog" 266// Import the native APIs. 267import napitest from "libentry.so" 268try { 269 let script: string = ` 270 createStringUtf16() 271 `; 272 hilog.info(0x0000, 'testJSVM', 'Test JSVM createStringUtf16: %{public}s', napitest.runJsVm(script)); 273} catch (error) { 274 hilog.error(0x0000, 'testJSVM', 'Test JSVM createStringUtf16 error: %{public}s', error.message); 275} 276``` 277 278### OH_JSVM_GetValueStringLatin1 279 280Use **OH_JSVM_GetValueStringLatin1** to convert a JS string into an ISO-8859-1-encoded string. 281 282CPP code: 283 284```cpp 285// hello.cpp 286#include "napi/native_api.h" 287#include "ark_runtime/jsvm.h" 288#include <hilog/log.h> 289// Register the GetValueStringLatin1 callback. 290static JSVM_CallbackStruct param[] = { 291 {.data = nullptr, .callback = GetValueStringLatin1}, 292}; 293static JSVM_CallbackStruct *method = param; 294// Set a property descriptor named getValueStringLatin1 and associate it with a callback. This allows the GetValueStringLatin1 callback to be called from JS. 295static JSVM_PropertyDescriptor descriptor[] = { 296 {"getValueStringLatin1", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 297}; 298// Define OH_JSVM_GetValueStringLatin1. 299// Set the maximum length of the string buffer. 300static const int MAX_BUFFER_SIZE = 128; 301static JSVM_Value GetValueStringLatin1(JSVM_Env env, JSVM_CallbackInfo info) 302{ 303 size_t argc = 1; 304 JSVM_Value args[1] = {nullptr}; 305 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 306 char buf[MAX_BUFFER_SIZE]; 307 size_t length; 308 JSVM_Value jsvmRes = nullptr; 309 JSVM_Status status = OH_JSVM_GetValueStringLatin1(env, args[0], buf, MAX_BUFFER_SIZE, &length); 310 if (status != JSVM_OK) { 311 OH_LOG_ERROR(LOG_APP, "JSVM GetValueStringLatin1 fail"); 312 } else { 313 OH_LOG_INFO(LOG_APP, "JSVM GetValueStringLatin1 success: %{public}s", buf); 314 } 315 OH_JSVM_CreateStringLatin1(env, buf, length, &jsvmRes); 316 return jsvmRes; 317} 318``` 319 320ArkTS code: 321 322```ts 323import hilog from "@ohos.hilog" 324// Import the native APIs. 325import napitest from "libentry.so" 326try { 327 // The ISO-8859-1 encoding does not support Chinese characters. If Chinese characters are passed in, garbled characters will be displayed. 328 let data = `"中文"`; 329 let script: string = `getValueStringLatin1(${data})`; 330 hilog.info(0x0000, 'testJSVM', 'Test JSVM getValueStringLatin1: %{public}s', napitest.runJsVm(script)); 331} catch (error) { 332 hilog.error(0x0000, 'testJSVM', 'Test JSVM getValueStringLatin1 error: %{public}s', error.message); 333} 334try { 335 // If non-character data is passed in, undefined will be returned. 336 let script: string = `getValueStringLatin1(10)`; 337 hilog.info(0x0000, 'testJSVM', 'Test JSVM getValueStringLatin1: %{public}s', napitest.runJsVm(script)); 338} catch (error) { 339 hilog.error(0x0000, 'testJSVM', 'Test JSVM getValueStringLatin1 error: %{public}s', error.message); 340} 341try { 342 // Passing in characters of other languages will not cause garbled characters. 343 let data = `"abo ABP=-&*/"`; 344 let script: string = `getValueStringLatin1(${data})`; 345 hilog.info(0x0000, 'testJSVM', 'Test JSVM getValueStringLatin1: %{public}s', napitest.runJsVm(script)); 346} catch (error) { 347 hilog.error(0x0000, 'testJSVM', 'Test JSVM getValueStringLatin1 error: %{public}s', error.message); 348} 349``` 350 351### OH_JSVM_CreateStringLatin1 352 353Use **OH_JSVM_CreateStringLatin1** to create a JS string from an ISO-8859-1-encoded C string. 354 355CPP code: 356 357```cpp 358// hello.cpp 359#include "napi/native_api.h" 360#include "ark_runtime/jsvm.h" 361#include <hilog/log.h> 362// Register the CreateStringLatin1 callback. 363static JSVM_CallbackStruct param[] = { 364 {.data = nullptr, .callback = CreateStringLatin1}, 365}; 366static JSVM_CallbackStruct *method = param; 367// Set a property descriptor named createStringLatin1 and associate it with a callback. This allows the CreateStringLatin1 callback to be called from JS. 368static JSVM_PropertyDescriptor descriptor[] = { 369 {"createStringLatin1", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 370}; 371// Set the maximum length of the string buffer. 372static const int MAX_BUFFER_SIZE = 128; 373// Define OH_JSVM_CreateStringLatin1. 374static JSVM_Value CreateStringLatin1(JSVM_Env env, JSVM_CallbackInfo info) 375{ 376 const char *str = "Hello, World! éçñ, successes to create Latin1 string! 111"; 377 size_t length = JSVM_AUTO_LENGTH; 378 JSVM_Value result = nullptr; 379 JSVM_Status status = OH_JSVM_CreateStringLatin1(env, str, length, &result); 380 if (status != JSVM_OK) { 381 OH_LOG_ERROR(LOG_APP, "JSVM CreateStringLatin1 fail"); 382 } else { 383 char buf[MAX_BUFFER_SIZE]; 384 size_t length; 385 OH_JSVM_GetValueStringLatin1(env, result, buf, MAX_BUFFER_SIZE, &length); 386 OH_LOG_INFO(LOG_APP, "JSVM CreateStringLatin1 success: %{public}s", buf); 387 } 388 return result; 389} 390``` 391 392ArkTS code: 393 394```ts 395import hilog from "@ohos.hilog" 396// Import the native APIs. 397import napitest from "libentry.so" 398try { 399 let script: string = `createStringLatin1()`; 400 hilog.info(0x0000, 'testJSVM', 'Test JSVM createStringLatin1: %{public}s', napitest.runJsVm(script)); 401} catch (error) { 402 hilog.error(0x0000, 'testJSVM', 'Test JSVM createStringLatin1 error: %{public}s', error.message); 403} 404``` 405<!--no_check-->