文档管理中心
您当前正在浏览新版开发者文档中心,目录分类和层级有所调整。点击左侧当前文档分类名称前的“☰”图标,可切换文档分类。 了解新版目录
指南与API参考指南NDK开发代码开发使用JSVM-API实现JS与C/C++语言交互JSVM-API使用指导使用JSVM-API接口提供Latin1/UTF16格式字符串相关开发

使用JSVM-API接口提供Latin1/UTF16格式字符串相关开发

简介

JSVM-API中新增创建和使用外部字符串的接口。

基本概念

在JSVM-API中,在用户提供的Latin1/UTF16格式字符串所在内存上直接创建对应的JavaScript字符串,和正常的JavaScript字符串能够进行同样的操作。

接口说明

展开
接口 功能说明
OH_JSVM_CreateExternalStringLatin1 使用ISO-8859-1编码的C字符串,创建一个外部的JavaScript字符串。
OH_JSVM_CreateExternalStringUtf16 使用UTF16-LE编码的C字符串,创建一个外部的JavaScript字符串。

使用示例

JSVM-API接口开发流程参考使用JSVM-API实现JS与C/C++语言交互开发流程,本文仅对接口对应C++相关代码进行展示。

创建外部字符串

cpp部分代码:

收起
自动换行
深色代码主题
复制
  1. #include <cstring>
  2. #include <string>
  3. static char stringLatin1[] = "hello";
  4. static char16_t stringUTF16[] = u"world";
  5. static JSVM_Value testExternalString(JSVM_Env env, JSVM_CallbackInfo info) {
  6. JSVM_VM vm;
  7. OH_JSVM_GetVM(env, &vm);
  8. JSVM_HandleScope handleScope;
  9. OH_JSVM_OpenHandleScope(env, &handleScope);
  10. JSVM_Value jsStrLatin1 = nullptr;
  11. bool copied = true;
  12. char buf[10];
  13. OH_JSVM_CreateExternalStringLatin1(env, stringLatin1, strlen(stringLatin1), nullptr, nullptr,
  14. &jsStrLatin1, &copied);
  15. OH_JSVM_GetValueStringUtf8(env, jsStrLatin1, buf, 10, nullptr);
  16. OH_LOG_INFO(LOG_APP, "created latin1 string is : %{public}s\n", buf);
  17. // 这里 copied 为 true 表示创建 external string 失败,否则表示创建成功
  18. OH_LOG_INFO(LOG_APP, "create external string failed : %{public}d\n", copied);
  19. copied = true;
  20. JSVM_Value jsStrUTF16 = nullptr;
  21. OH_JSVM_CreateExternalStringUtf16(env, stringUTF16, std::char_traits<char16_t>::length(stringUTF16),
  22. nullptr, nullptr, &jsStrUTF16, &copied);
  23. OH_JSVM_GetValueStringUtf8(env, jsStrUTF16, buf, 10, nullptr);
  24. OH_LOG_INFO(LOG_APP, "created utf16 string is : %{public}s\n", buf);
  25. // 这里 copied 为 true 表示创建 external string 失败,否则表示创建成功
  26. OH_LOG_INFO(LOG_APP, "create external string failed : %{public}d\n", copied);
  27. OH_JSVM_CloseHandleScope(env, handleScope);
  28. return nullptr;
  29. }
  30. static JSVM_CallbackStruct param[] = {
  31. {.data = nullptr, .callback = testExternalString},
  32. };
  33. static JSVM_CallbackStruct *method = param;
  34. // wrapperObject方法别名,供JS调用
  35. static JSVM_PropertyDescriptor descriptor[] = {
  36. {"testExternalString", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
  37. };
  38. // 样例测试JS
  39. const char *srcCallNative = R"JS(testExternalString();)JS";

预期输出结果

收起
自动换行
深色代码主题
复制
  1. created latin1 string is : hello
  2. create external string failed: 0
  3. created utf16 string is : world
  4. create external string failed: 0