往期鸿蒙全套实战文章必看:(文中附带全栈鸿蒙学习资料)
场景介绍
开发者通过createJsCore方法来创建一个新的JS基础运行时环境,并通过该方法获得一个CoreID,通过evaluateJS方法使用CoreID对应的运行环境来运行JS代码,在JS代码中创建promise并异步调取TS侧设定的callback函数,最后使用releaseJsCore方法来释放CoreID对应的运行环境。
使用示例
1.接口声明和编译配置
接口声明
// index.d.ts
export const createJsCore: (fun: Function) => number;
export const releaseJsCore: (a: number) => void;
export const evaluateJS: (a: number, str: string) => string;
编译配置
// CMakeLists.txt
# the minimum version of CMake.
cmake_minimum_required(VERSION 3.4.1)
project(MyApplication)
set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
if(DEFINED PACKAGE_FIND_FILE)
include(${PACKAGE_FIND_FILE})
endif()
include_directories(${NATIVERENDER_ROOT_PATH}
${NATIVERENDER_ROOT_PATH}/include)
add_library(entry SHARED create_jsvm_runtime.cpp)
target_link_libraries(entry PUBLIC libace_napi.z.so libjsvm.so libhilog_ndk.z.so)
2.新建多个JS运行时环境并运行JS代码
// create_jsvm_runtime.cpp
#include "napi/native_api.h"
#include "ark_runtime/jsvm.h"
#include <bits/alltypes.h>
#include <deque>
#include <map>
#include <unistd.h>
#include <hilog/log.h>
#include <cstring>
#include <string>
#include <vector>
#include <sstream>
#define LOG_TAG "TEST_TAG"
// 用于获取并抛出最后一个错误信息。通过OH_JSVM_GetLastErrorInfo获取错误信息,
// 如果没有挂起的异常且错误信息存在,则通过 OH_JSVM_ThrowError 抛出错误。
#define GET_AND_THROW_LAST_ERROR(env) \
do { \
const JSVM_ExtendedErrorInfo* errorInfo = nullptr; \
OH_JSVM_GetLastErrorInfo((env), &errorInfo); \
bool isPending = false; \
OH_JSVM_IsExceptionPending((env), &isPending); \
JSVM_Value error; \
if (isPending && JSVM_OK == OH_JSVM_GetAndClearLastException((env), &error)) { \
\
JSVM_Value stack; \
OH_JSVM_GetNamedProperty((e