目录

How do I dynamically load a .so library in ArkTS and C/C++ at runtime?

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: