Answer
1. Use dynamic import to load a .so library in ArkTS.
2. Use dlopen to dynamically load a .so library in C/C++.
Sample code:
1. Use dynamic import to load a .so library in ArkTS. Add an asynchronous function with let testNapi = await import ("libentry.so") to dynamically load the .so library.
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") // Load so library
hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.default.add(2, 3)); // Call library functions by default
// hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.add(2, 3));
})
}
.width('100%')
}
.height('100%')
}
} 2. Use dlopen to dynamically load a .so library in C/C++.
For example, to call the add() function in liba.so, do as follows:

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 = this.getUIContext().getHostContext()!.bundleCodeDir; // Get project path
hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.addByLibPath(2, 3, path + '/libs/arm64/liba.so')); // Transfer parameter path information to the native side
})
}
.width('100%')
}
.height('100%')
}
} #include "napi/native_api.h"
#include <dlfcn.h>
typedef double (*FUNC_ADD)(int, int);
static napi_value AddByLibPath(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); // Obtain dynamic library path information
void *handle = dlopen(path, RTLD_LAZY); // Open a dynamic link library, The path is "path".
dlerror();
FUNC_ADD add_func = (FUNC_ADD)dlsym(handle, "add"); // Retrieve the function named "add"
if (dlerror()) {
return nullptr;
}
double res = add_func(value0, value1); // Call add and pass the parameter information
dlclose(handle); // Close the dynamic library
napi_value sum;
napi_create_double(env, res, &sum);
return sum;
}
// ...