目录

loadNativeModule (Synchronously and Dynamically Loading a System Library)

This module provides the capability of synchronously and dynamically loading a system library.

The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version.

loadNativeModule

loadNativeModule(moduleName: string): Object

The loadNativeModule API is used to synchronously and dynamically load a native module, so as to load the required module on demand.

System capability: SystemCapability.Utils.Lang

Parameters

Name Type Mandatory Description
moduleName string Yes Name of the module to load.

Return value

Type Description
Object Default export of the native module, which must be received using the ESObject type of ArkTS.

Error codes

For details about the error codes, see Universal Error Codes and Utils Error Codes.

ID Error Message
401 The parameter check failed.
10200301 Loading native module failed.

Scenarios supported by loadNativeModule

Scenario Example
System library module Load @ohos. or @system..
Native module in an application Load libNativeLibrary.so.

[h2]Usage Notes

Take loading libentry.so as an example. The following configurations are required.

  1. Configure the dependencies field in the module-level oh-package.json5 file. For details, see Module-level oh-package.json5.

    {
      "dependencies": {
        "libentry.so": "file:./src/main/cpp/types/libentry"
      }
    }
  2. Configure the runtimeOnly.packages field in the module-level build-profile.json5 file. For details, see Module-level build-profile.json5 File.

    {
      "buildOption": {
        "arkOptions": {
          "runtimeOnly": {
            "packages": [
              "libentry.so"
            ]
          }
        }
      }
    }

Example 1: Loading a System Library Module to a HAP

let hilog: ESObject = loadNativeModule("@ohos.hilog");
hilog.info(0, "testTag", "loadNativeModule ohos.hilog success");

Example 2: 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;

After completing the dependency configuration in Usage Notes, use loadNativeModule to load libentry.so and call the add function.

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