解决措施
1.ArkTS 可以通过动态 import 加载 so 库。
2.Native侧可以使用dlopen动态加载so库。
参考代码如下:
1.ArkTS 通过动态 import 加载 so 库。添加异步函数,在异步函数中通过let testNapi = await import(“libentry.so”)实现动态加载so库。
import { hilog } from '@kit.PerformanceAnalysisKit';
// import testNapi from 'libentry.so';
@Entry
@Component
struct LoadSoLibrary {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(async() => {
let testNapi = await import("libentry.so") // 加载so库
hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.default.add(2, 3)); // 通过default调用库函数
// hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.add(2, 3));
})
}
.width('100%')
}
.height('100%')
}
}
2.Native侧使用dlopen动态加载so库。
需要调用liba.so中的add函数。
-
将liba.so文件放到libs/arm64-v8a/路径下。
-
需要在ArkTS侧传递so库路径信息到Native侧。
import { hilog } from '@kit.PerformanceAnalysisKit';
import testNapi from 'libentry.so';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let path = getContext(this).bundleCodeDir; // 获取项目路径
hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.addByLibPath(2, 3, path + '/libs/arm64/liba.so')); // 传递参数路径信息到Native侧
})
}
.width('100%')
}
.height('100%')
}
}
- 然后在Native侧通过dlopen函数动态加载so库。
#include "napi/native_api.h"
#include <dlfcn.h>
typedef double (*FUNC_ADD)(int, int);
static napi_value Add(napi_env env, napi_callback_info info) {
size_t requireArgc = 3;
size_t argc = 3;
napi_value args[3] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
double value0;
napi_get_value_double(env, args[0], &value0);
double value1;
napi_get_value_double(env, args[1], &value1);
char path[255];
size_t size = 255;
napi_get_value_string_utf8(env, args[2], path, 255, &size); // 获取动态库路径信息
void *handle = dlopen(path, RTLD_LAZY); // 打开一个动态链接库.路径为path
dlerror();
FUNC_ADD add_func = (FUNC_ADD)dlsym(handle, "add"); // 获取函数名为add的函数
if (dlerror()) {
return nullptr;
}
double res = add_func(value0, value1); // 调用add并传递参数信息
dlclose(handle); // 最后关闭动态库
napi_value sum;
napi_create_double(env, res, &sum);
return sum;
}
// ...