1# 使用JSVM-API接口提供Latin1/UTF16格式字符串相关开发 2<!--Kit: NDK Development--> 3<!--Subsystem: arkcompiler--> 4<!--Owner: @yuanxiaogou; @string_sz--> 5<!--Designer: @knightaoko--> 6<!--Tester: @test_lzz--> 7<!--Adviser: @fang-jinxu--> 8 9## 简介 10 11JSVM-API中新增创建和使用外部字符串的接口。 12 13## 基本概念 14 15在JSVM-API中,在用户提供的Latin1/UTF16格式字符串所在内存上直接创建对应的JavaScript字符串,和正常的JavaScript字符串能够进行同样的操作。 16 17## 接口说明 18 19| 接口 | 功能说明 | 20|----------------------------------------|--------------------------------| 21| OH_JSVM_CreateExternalStringLatin1 | 使用ISO-8859-1编码的C字符串,创建一个外部的JavaScript字符串。 | 22| OH_JSVM_CreateExternalStringUtf16 | 使用UTF16-LE编码的C字符串,创建一个外部的JavaScript字符串。 | 23 24## 使用示例 25 26JSVM-API接口开发流程参考[使用JSVM-API实现JS与C/C++语言交互开发流程](use-jsvm-process.md),本文仅对接口对应C++相关代码进行展示。 27 28### 使用接口判断是否是Number Object 29 30cpp部分代码 31 32```cpp 33#include <cstring> 34#include <string> 35static char stringLatin1[] = "hello"; 36static char16_t stringUTF16[] = u"world"; 37 38static JSVM_Value testExternalString(JSVM_Env env, JSVM_CallbackInfo info) { 39 JSVM_VM vm; 40 OH_JSVM_GetVM(env, &vm); 41 42 JSVM_HandleScope handleScope; 43 OH_JSVM_OpenHandleScope(env, &handleScope); 44 JSVM_Value jsStrLatin1 = nullptr; 45 bool copied = true; 46 char buf[10]; 47 OH_JSVM_CreateExternalStringLatin1(env, stringLatin1, strlen(stringLatin1), nullptr, nullptr, 48 &jsStrLatin1, &copied); 49 OH_JSVM_GetValueStringUtf8(env, jsStrLatin1, buf, 10, nullptr); 50 OH_LOG_INFO(LOG_APP, "created latin1 string is : %{public}s\n", buf); 51 // 这里 copied 为 true 表示创建 external string 失败,否则表示创建成功 52 OH_LOG_INFO(LOG_APP, "create external string failed : %{public}d\n", copied); 53 copied = true; 54 JSVM_Value jsStrUTF16 = nullptr; 55 OH_JSVM_CreateExternalStringUtf16(env, stringUTF16, std::char_traits<char16_t>::length(stringUTF16), 56 nullptr, nullptr, &jsStrUTF16, &copied); 57 OH_JSVM_GetValueStringUtf8(env, jsStrUTF16, buf, 10, nullptr); 58 OH_LOG_INFO(LOG_APP, "created utf16 string is : %{public}s\n", buf); 59 // 这里 copied 为 true 表示创建 external string 失败,否则表示创建成功 60 OH_LOG_INFO(LOG_APP, "create external string failed : %{public}d\n", copied); 61 OH_JSVM_CloseHandleScope(env, handleScope); 62 63 return nullptr; 64} 65 66static JSVM_CallbackStruct param[] = { 67 {.data = nullptr, .callback = testExternalString}, 68}; 69 70static JSVM_CallbackStruct *method = param; 71 72// wrapperObject方法别名,供JS调用 73static JSVM_PropertyDescriptor descriptor[] = { 74 {"testExternalString", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 75}; 76 77// 样例测试JS 78const char *srcCallNative = R"JS(testExternalString();)JS"; 79 80``` 81 82## 预期输出结果 83``` 84created latin1 string is : hello 85create external string failed: 0 86created utf16 string is : world 87create external string failed: 0 88``` 89