目录

Node-API Development Process

To implement cross-language interaction using Node-API, you need to register and load modules based on the Node-API mechanism first.

The following demonstrates how to implement cross-language interaction by calling callNative() in ArkTS/JS code and implementing CallNative() in native code.

Creating a Native C++ Project

Implementing Native APIs

You do not need to copy the above code as it is pre-configured in the napi_init.cpp file when the native C++ project is created.

Calling C/C++ APIs on ArkTS

On ArkTS, import the .so file that contains the processing logic on the native side to use C/C++ APIs.

// entry/src/main/ets/pages/Index.ets
// Import the native APIs.
import nativeModule from 'libentry.so'

@Entry
@Component
struct Index {
  @State message: string = 'Test Node-API callNative result: ';
  @State message2: string = 'Test Node-API nativeCallArkTS result: ';
  build() {
    Row() {
      Column() {
        // Pressing the first button calls callNative(), which uses CallNative() in the native code to add the two numbers.
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.message += nativeModule.callNative(2, 3);
            })
        // Pressing the second button calls nativeCallArkTS, which corresponds to NativeCallArkTS in the native code. The ArkTS function is called on the native side.
        Text(this.message2)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.message2 += nativeModule.nativeCallArkTS((a: number)=> {
                return a * 2;
            });
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

Node-API Constraints

[h2]Naming Rules of .so Files

The case of the module name to import must be the same as that registered. For example, if the module name is entry, the .so file name must be libentry.so, and the nm_modname field in napi_module must be entry. When importing the module in ArkTS, use **import **xxx from 'libentry.so'.

[h2]Registration

[h2]Multithread Processing

Each engine instance corresponds to an ArkTS thread. The objects of an instance cannot be operated across threads. Otherwise, the application crashes. Observe the following rules:

[h2]Debugging Device Selection

You are advised to use a real device for code debugging. If no real device is available or you do not have the permission to use a real device, use an emulator for debugging. For details about the problems that may occur during emulator debugging, see Bundle Manager.

The previewer is mainly used to debug UI components. Do not use it for function debugging. Otherwise, the following error message may be displayed:

Maintenance and testing measures have been added to address common errors. For details, see Analyzing Exceptions and Crashes Using Node-API.