openharmony 鸿蒙 js-apis-load-native-module

2025-06-06 浏览 (1)

Dynamically Loading Native Modules in Synchronous Mode

The loadNativeModule API is used to dynamically load native modules in synchronous mode. It is used to load native modules only when needed, preventing unnecessary modules from being loaded during application startup. However, using this API incurs a delay due to the loading of the .so file, and therefore you need to assess whether this will impact functionality.

API Description

loadNativeModule(moduleName: string): Object;
ParameterDescription
moduleNameName of the module to load.

NOTE

The name of the module loaded by loadNativeModule is the name provided in dependencies in the oh-package.json5 file of the dependency.

loadNativeModule can be used only to load modules in the UI main thread.

Dependencies must be configured for the API call regardless of whether the input parameter is a constant string or variable expression.

Supported Scenarios

ScenarioExample
System library moduleLoad @ohos. or @system..
Native module in an applicationLoad libNativeLibrary.so.

Usage Example

  • Loading a system library module to a HAP

    let hilog: ESObject = loadNativeModule("@ohos.hilog");
    hilog.info(0, "testTag", "loadNativeModule ohos.hilog success");
    
  • Loading a native library to a HAP

    The index.d.ts file of libentry.so is as follows:

    //index.d.ts
    export const add: (a: number, b: number) => number;
    
  1. When loading a local .so library, configure dependencies in the oh-package.json5 file.

    {
        "dependencies": {
            "libentry.so": "file:../src/main/cpp/types/libentry"
        }
    }
    
  2. Configure the build-profile.json5 file.

    {
        "buildOption" : {
            "arkOptions" : {
                "runtimeOnly" : {
                    "packages": [
                        "libentry.so"
                    ]
                }
            }
        }
    }
    
  3. Use loadNativeModule to load libentry.so and call the add function.

    let module: ESObject = loadNativeModule("libentry.so");
    let sum: number = module.add(1, 2);
    

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArkTS

harmony 鸿蒙Configuring arkOptions in build-profile.json5

harmony 鸿蒙Asynchronous Lock

harmony 鸿蒙Ark Bytecode File Format

harmony 鸿蒙Naming Conventions for Ark Bytecode Functions

harmony 鸿蒙Ark Bytecode Fundamentals

harmony 鸿蒙Overview of Ark Bytecode

harmony 鸿蒙Shared Container

harmony 鸿蒙Asynchronous Waiting

harmony 鸿蒙ArkTS Cross-Language Interaction

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/Yrk6S5