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