HOME
Shop
  • English
  • 简体中文
HOME
Shop
  • English
  • 简体中文
  • Product Series

    • FPGA+ARM

      • GM-3568JHF

        • Introduction

          • GM-3568JHF Introduction
        • Quick Start

          • Preface
          • Environment Setup
          • Compilation Notes
          • Flashing Guide
          • Debugging Tools
          • Software Update
          • Viewing System Information
          • Test Commands
          • Application Compilation
          • Source Code Access
        • Peripherals & Interfaces

          • USB
          • Display and Touch
          • Ethernet
          • WIFI
          • Bluetooth
          • TF-Card
          • Audio
          • Serial Port
          • CAN
          • RTC
        • Application Development

          • UART Read/Write Demo
          • Key Detection Demo
          • LED Blink Demo
          • MIPI Screen Detection Demo
          • Read USB Device Information Demo
          • FAN Detection Demo
          • FPGA FSPI Communication Demo
          • FPGA DMA Read/Write Demo
          • GPS Debugging Demo
          • Ethernet Test Demo
          • RS485 Read/Write Demo
          • FPGA I2C Read/Write Demo
          • PN532 NFC Card-Reading Demo
          • TF Card Read/Write Demo
        • QT Development

          • ARM64 Cross-Compiler Environment Setup
          • Adding a QT Program to Boot Auto-Start
        • RKNN_NPU Development

          • RK3568 NPU Overview
          • Development Environment Setup
          • Run the Official YOLOv5 Example
        • FPGA Development

          • ARM and FPGA Communication
          • FPGA Development Manual
        • Others

          • Modifying the Root Filesystem
          • System Auto-Start Services
        • Downloads

          • Downloads
      • MB-E30P

        • Introduction

          • MB-E30P Introduction
        • Quick Start

          • Preface
          • Environment Setup
          • Compilation Instructions
          • Flashing Guide
          • Debugging Tools
          • Software Update
          • Viewing Information
          • Test Commands
          • Application Compilation
          • Source Code Acquisition
        • Peripherals & Interfaces

          • USB
          • Display and Touch
          • Ethernet
          • WIFI
          • Bluetooth
          • TF-Card
          • Audio
          • RTC
        • Application Development

          • Key Detection Demo
          • LED Blink Demo
          • MIPI Screen Detection Demo
          • Read USB Device Information Demo
          • FAN Detection Demo
          • FPGA FSPI Communication Demo
          • FPGA DMA Read/Write Demo
          • Ethernet Test Demo
          • FPGA IIC Read/Write Demo
          • PN532 NFC Card Reading Demo
          • TF Card Read/Write Demo
        • QT Development

          • ARM64 Cross-Compiler Environment Setup
          • Adding a QT Program to the Boot Auto-Start Service
        • RKNN_NPU Development

          • RK3568 NPU Overview
          • Development Environment Setup
          • Run the Official YOLOv5 Example
          • Model Conversion In Detail
          • Run Custom Models on the Board
        • FPGA Development

          • ARM and FPGA Communication
          • FPGA Development Manual
        • Others

          • Modifying the Root Filesystem
          • System Auto-Start Service
        • Downloads

          • Downloads
    • ShimetaPi

      • M4-R1

        • Introduction

          • M4-R1 Introduction
        • Quick Start

          • OpenHarmony Overview
          • Image Burning
          • Application Development Quick Start
          • Device Development Quick Start
        • Application Development

          • ArkUI

            • ArkTS Language Overview
            • UI Components - Row Container Introduction
            • UI Components - Column Container Introduction
            • UI Components - Text Component
            • UI Components - Toggle Component
            • UI Components - Slider Component
            • UI Components - Animation Component & Transition Component
          • Documentation

            • OpenHarmony Official Materials
          • Development Notes

            • Full-SDK Replacement Tutorial
            • Introducing and Using Third-Party Libraries
            • HDC Debugging
            • Restore Factory Mode via Command Line
            • Upgrade App to System Permission
          • First App

            • Build Your First ArkTS Application - HelloWorld
          • Demos

            • Serial-Debug-Assistant Application Demo
            • Writing-Board Application Demo
            • Digital Clock Application Demo
            • Wi-Fi Information Acquisition Application Demo
        • Device Development

          • Ubuntu Development

            • Environment Setup
            • Download Source Code
            • Compile Source Code
          • DevEco Device Tool

            • Tool Introduction
            • Development Environment Construction
            • Import the SDK
            • HUAWEI DevEco Tool Function Introduction
        • Kernel Peripherals & Interfaces

          • Guide
          • Device Tree Introduction
          • NAPI Introduction
          • ArkTS Introduction
          • NAPI Development Hands-on Demo
          • GPIO Introduction
          • I2C Communication
          • SPI Communication
          • PWM Control
          • UART Communication
          • TF Card (MicroSD)
          • Screen (Display)
          • Touch
          • Ethernet
          • M.2 SSD
          • Audio
          • WIFI & BT
          • Camera
        • Downloads

          • Downloads
      • M5-R1

        • Introduction

          • M5-R1 Development Docs
        • Quick Start

          • Image Burning
          • Environment Setup
          • Download Source Code
        • Peripherals & Interfaces

          • Raspberry Pi Interfaces
          • GPIO Interface
          • I2C Interface
          • SPI Communication
          • PWM Control
          • Serial Port Communication
          • TF Card
          • Display
          • Touch
          • Audio
          • RTC
          • Ethernet
          • M.2
          • MINI-PCIE
          • Camera
          • WIFI & BT
        • Downloads

          • Downloads
      • Pico-G1

        • Product Overview

          • Product Introduction
          • SDK Version Information
        • Quick Start

          • Development Environment Setup
          • Image Build
          • Image Flashing
          • System Login
          • Network Configuration
          • File Transfer
          • SDK Directory Structure
          • Deploying Your First Application
          • Deploying Your First Driver
          • Mounting an SD Card
        • Peripherals & Interfaces

          • GPIO Control
          • UART Serial Communication
          • I2C Communication
          • SPI Communication
        • MPP Media Development

          • MPP Media Processing Software
          • Image Processing Chain
          • Video Input
          • Image Encoding
        • NPU & AI

          • NPU Driver and Runtime Library Architecture
          • .xmm Model Loading
          • SVP Video Processing
          • AI Noise Reduction (AI_NR)
        • Application Samples

          • Encryption/Decryption Application
          • ADC Acquisition Application
          • Low-Power Application
          • Audio Processing Application
          • Video Encoding Application
          • Video Input Application
          • Video Graphics Subsystem (VGS) Application
          • 08 Region Overlay Application
          • 09 Intelligent Video Engine Application
          • 10 UVC Webcam Application
          • 11 All-in-One Quickstart Application
          • 12 FPN Correction Application
          • 13 Regional Motion Detection Application
          • 14 MTCNN Face Detection Application
        • Expansion Board Peripheral Examples

          • 00 - Pico Expansion Board Peripheral Examples Overview
          • 01 - OLED Display Application
          • 02 - TFT Display Application
          • 03 - MPU6050 Gyroscope Application
          • 04 - ADC Acquisition Application
          • 05 - Passive Buzzer Application
          • 06 - MQ Gas Sensor Application
          • 07 - GPS Positioning Application
          • 08 - SHT20 Temperature & Humidity Application
          • 09 - Ultrasonic Ranging Application
          • 10 - SpO2 Sensor Application
          • 11 - DC Motor Control Application
          • 12 - Servo Control Application
    • OpenHarmony

      • SC-3568HA

        • Introduction

          • SC-3568HA Overview
        • Quick Start Guide

          • OpenHarmony Overview
          • Image Flashing
          • Setting Up the Development Environment
          • Hello World Application and Deployment
        • Application Development

          • ArkUI

            • Introduction to ArkTS Language
            • Introduction to UI Components and Practical Applications (Part 1)
            • Introduction to UI Components and Practical Applications (Part 2)
            • Introduction to UI Components and Practical Applications (Part 3)
          • Expand

            • Getting Started Guide
            • Referencing and Using Third-Party Libraries
            • Application Compilation and Deployment
            • Command-Line Factory Reset
            • System Debugging -- HDC Debugging
            • APP Stability Testing
            • Chapter 7 Application Testing
        • Device Development

          • Environment Setup
          • Download Source Code
          • Compiling Source Code
        • Peripheral And Interface

          • Raspberry Pi interface
          • GPIO Interface
          • I2C Interface
          • SPI communication
          • PWM (Pulse Width Modulation) control
          • Serial port communication
          • TF Card
          • Display Screen
          • Touch
          • Audio
          • RTC
          • Ethernet
          • M.2
          • MINI-PCIE
          • Camera
          • WIFI&BT
          • Raspberry Pi expansion board
        • Downloads

          • Downloads
      • M-K1HSE

        • Introduction

          • M-K1HSE Introduction
        • Quick Start

          • Development environment construction
          • Source code acquisition
          • Compilation Notes
          • Burning Guide
        • Application Development

          • Application Development Environment Setup
          • First Application - Hello World
        • Peripherals and interfaces

          • 01 Audio
          • 02 RS485
          • 03 Display
        • System customization development

          • System transplant
          • System customization
          • Driver Development
          • System Debugging
          • OTA Update
        • Downloads

          • Downloads
    • HVS Camera

      • Quick Start

        • SDK Overview
        • Downloads
        • Your First C++ Program
        • Python Data Analysis
        • MultiVision Studio
      • Development

        • Programming Guides

          • Open Camera
          • Read Events
          • Recording & Replay
          • Event Processing (Denoising)
          • Display & Visualization
          • Tuning
          • Capture APS Image
        • Toolkit SDK

          • Hybrid Vision Toolkit
          • Quick Start
          • C++ API
          • Python API
        • Algorithm

          • Hybrid Vision Algo
          • Hybrid Vision Algo API
          • Windows Algo SDK
        • Samples Overview
        • Applications
      • Fundamentals

        • Event Camera Fundamentals
        • HVS Hybrid Vision
        • Event Visualization
        • Data Formats Reference
        • Glossary
        • Bias & Tuning
        • Video Tutorials
      • USB Cameras

        • HVS Camera Quick Start
        • Networking Capabilities

          • HVS Camera System Architecture
          • EVS Network Server
          • EVS Time Sync
          • Web Window
        • HVS Camera Compatibility Matrix
        • FAQ & Troubleshooting Guide
        • Products

          • CF-NRS1 (Lingguang No.1 Hybrid Vision Camera)
      • MIPI Modules

        • MIPI Module Quick Start
        • Carrier Boards

          • RDK X5 Carrier Board Adaptation
          • Raspberry Pi Carrier Board Adaptation
          • Digua Pi Carrier Board Adaptation
          • ShimeTai Board Carrier Board Adaptation
        • MIPI Module Compatibility Matrix
        • Products

          • EVS_003 Sensor Module
    • AI-model

      • 1684XB-32T

        • Introduction

          • AIBOX-1684XB-32 Introduction
        • Quick Start

          • First Use
          • Network Configuration
          • Disk Usage
          • Memory Allocation
          • Fan Control Strategy
          • Firmware Upgrade
          • Cross Compilation
          • Model Quantization
        • Application Development

          • Development Overview

            • Sophgo SDK Development
            • Sophgo Demo Introduction
          • Large Language Models

            • Deploying Llama3 Example
            • Sophon LLM_api_server Development
            • Deploying MiniCPM-V-2_6
            • Qwen-2-5-VL Image and Video Recognition Demo
            • Qwen3-chat Demo
            • Qwen3-Qwen Agent-MCP Development
            • Qwen3-langchain-AI Agent
          • Deep Learning

            • ResNet (Image Classification)
            • LPRNet (License Plate Recognition)
            • SAM (General Image Segmentation Foundation Model)
            • YOLOv5 (Object Detection)
            • OpenPose (Human Keypoint Detection)
            • PP-OCR (Optical Character Recognition)
        • Downloads

          • Downloads
      • 1684X-416T

        • Introduction

          • AIBOX-1684X-416 Introduction
        • Demo Quick Guide

          • ShimeTai Intelligent Monitoring Demo Quick Usage Guide
      • RDK-X5

        • Introduction

          • RDK-X5 Hardware Introduction
        • Quick Start

          • RDK-X5 Quick Start
        • Application Development

          • AI Online Model Development

            • Experiment 01 - Access Volcengine Doubao AI
            • Experiment 02 - Image Analysis
            • Experiment 03 - Multimodal Visual Analysis & Localization
            • Experiment 04 - Multimodal Image-Text Comparison
            • Experiment 05 - Multimodal Document/Table Analysis
            • Experiment 06 - Camera-based AI Visual Analysis
          • Large Language Models

            • Experiment 01 - Speech Recognition
            • Experiment 02 - Voice Conversation
            • Experiment 03 - Multimodal Image Analysis - Voice
            • Experiment 04 - Multimodal Image Comparison - Voice
            • Experiment 05 - Multimodal Document Analysis - Voice
            • Experiment 06 - Multimodal Vision Application - Voice
          • ROS2 Basics

            • Experiment 01 - Environment Setup
            • Experiment 02 - Create & Build a Workspace Package
            • Experiment 03 - Run ROS2 Topic Communication Node
            • Experiment 04 - ROS2 Camera Application
          • 40-pin IO Development

            • Experiment 01 - GPIO Output (LED Blink)
            • Experiment 02 - GPIO Input
            • Experiment 03 - Button-controlled LED
            • Experiment 04 - PWM Output
            • Experiment 05 - Serial Output
            • Experiment 06 - I2C Experiment
            • Experiment 07 - SPI Experiment
          • USB Module Usage

            • Experiment 01 - USB Voice Module Usage
            • Experiment 02 - Sound Source Localization Module
          • Machine Vision Practice

            • Experiment 01 - Open USB Camera
            • Experiment 02 - Color Recognition
            • Experiment 03 - Gesture Recognition
            • Experiment 04 - YOLOv5 Object Detection
      • RDK-S100

        • Introduction

          • RDK-S100 Hardware Introduction
        • Quick Start

          • RDK-S100 Quick Start
        • Application Development

          • AI Online Model Development

            • Experiment 01 - Access Volcengine Doubao AI
            • Experiment 02 - Image Analysis
            • Experiment 03 - Multimodal Visual Analysis & Localization
            • Experiment 04 - Multimodal Image-Text Comparison
            • Experiment 05 - Multimodal Document/Table Analysis
            • Experiment 06 - Camera-based AI Visual Analysis
          • Large Language Models

            • Experiment 01 - Speech Recognition
            • Experiment 02 - Voice Conversation
            • Experiment 03 - Multimodal Image Analysis - Voice
            • Experiment 04 - Multimodal Image Comparison - Voice
            • Experiment 05 - Multimodal Document Analysis - Voice
            • Experiment 06 - Multimodal Vision Application - Voice
          • ROS2 Basics

            • Experiment 01 - Environment Setup
            • Experiment 02 - Create & Build a Workspace Package
            • Experiment 03 - Run ROS2 Topic Communication Node
            • Experiment 04 - ROS2 Camera Application
          • 40-pin IO Development

            • Experiment 01 - GPIO Output (LED Blink)
            • Experiment 02 - GPIO Input
            • Experiment 03 - Button-controlled LED
            • Experiment 04 - PWM Output
            • Experiment 05 - Serial Output
            • Experiment 06 - I2C Experiment
            • Experiment 07 - SPI Experiment
          • USB Module Usage

            • Experiment 01 - USB Voice Module Usage
            • Experiment 02 - Sound Source Localization Module
          • Machine Vision Practice

            • Experiment 01 - Open USB Camera
            • Experiment 02 - Image Processing Basics
            • Experiment 03 - Object Detection
            • Experiment 04 - Image Segmentation
      • RK1828

        • Introduction

          • M5-182X-A1 AI Edge Box - Product Introduction
          • M5-182X-A1 Hardware Specifications
          • M5-182X-A1 Usage & Safety
        • Quick Start

          • M5-182X-A1 Image Flashing
          • RK182X Hardware Installation & Verification
          • RK182X Development Environment Quick Setup
          • RK182X SDK Overview
          • RK182X Environment Setup in Detail
          • RK182X Quick Start
          • Vendor SDK Data Extraction Record
        • Development Guide

          • ClawChips Architecture and Principles
          • SKILL User Manual
          • RK182X Series LLM Inference (RK1828 Model)
          • RK182X Series CNN Inference (RK1828 Model)
          • Model Conversion
          • RK182X AI Agent Application Development Guide
          • RK182X Industrial Anomaly Detection Application
        • SDK Reference

          • RKNN3-SDK Overview

            • RKNN3 SDK Overview
          • RKNN3-Toolkit

            • RKNN3 Toolkit Installation and Usage
          • RKLLM

            • RKLLM On-Device LLM Inference
          • RK182X Series NPU Overview and Architecture (RK1828 Model)
          • RK182X INT8 Quantized Inference Deployment
          • RK182X MPP Multimedia Framework
          • MPP Details

            • RK182X Video Decoding
            • RK182X Video Encoding
          • NPU Details

            • RKNN Model Conversion
            • RK182X NPU INT8 Quantized Inference
            • RK182X Multi-Model Parallel Inference
          • RGA Details

            • RK182X RGA 2D Graphics Acceleration
          • VPU Details

            • RK182X VPU Codec
        • Hardware Reference

          • RK182X Series Hardware Architecture Overview (RK1828 Model)
          • RK182X Pin Definitions and Multiplexing Configuration
          • RK182X Pin Definitions
          • RK182X Power Management
          • RK182X Clock and PLL Configuration
          • RK182X Clock and Frequency Configuration
        • Tutorials

          • Hello World
          • Hello RK1828 - The First Program
          • RTSP Streaming
          • RTSP Streaming + AI Analysis
          • ShiMetaPi AI Lobster One-Click Deployment
          • PaddleOCR-VL Text Recognition
          • Qwen3-1.7B LLM Text Chat
          • AI Multi-View Inspection (Qwen3-VL Wrapper)
          • YOLOv5 Object Detection
        • Downloads

          • Downloads
        • FAQ

          • FAQ
    • Core-Board

      • C-3568BQ

        • Introduction

          • C-3568BQ Overview
      • C-3588LQ

        • Introduction

          • C-3588LQ Overview
      • GC-3568JBAF

        • Introduction

          • GC-3568JBAF Overview
      • C-K1BA

        • Introduction

          • C-K1BA Overview
    • Software Platform

      • ShiMetaPi Workbench

        • Introduction

          • Product Overview
          • Core Architecture
          • Feature Entries
          • Supported Hardware
          • Release Notes
        • Quick Start

          • Install & Login
          • Connect the Device
          • Set Up the Environment
          • Connect to AIHub
          • First Inference
        • User Guide

          • Workspace Overview
          • Device Manager
          • Model Market
          • One-Click Deploy
          • Vision — SVP
          • Vision - Custom Models
          • shimeta-py IDE
          • Terminal
          • Agent Debug Assistant
          • Settings and Resources
        • FAQ

          • Installation & Login
          • Device Connection
          • Models & Deployment
          • Vision & Runtime
          • Settings & Other
      • ShimetaPi Repository

        • Introduction

          • ShimetaPi Software Repository
        • Pico G1 (GK7206)

          • Quick Start

            • Installation & First Inference
            • shimeta_infer — Image Inference
            • shimeta_camera — Real-time Camera Inference
            • SVP Scene Detection
            • File Transfer & Built-in Model Reference
            • FAQ
          • HTTP API & Python SDK

            • HTTP API Reference
      • Model Fine-tuning Platform

        • Introduction

          • Model Training Platform
        • Quick Start

          • Register & Login
          • Create Your First Model (30-Minute Quick Experience)
        • Training Guide

          • Data Preparation & Annotation
          • Training Parameter Configuration
          • Start & Monitor Training
          • Model Evaluation & Testing
        • Model Deployment

          • Export Model
          • Deploy to Edge Device

NAPI Introduction

Part One: NAPI Basic Concept Introduction

NAPI in OpenHarmony (extended from the Node.js N-API framework) is part of the ArkUI subsystem under the UI framework. It is used to interact between code written in JS/ETS languages and native code (C/C++). NAPI is suitable for encapsulating IO, CPU-intensive, OS low-level, and other capabilities and exposing JS interfaces externally. Through NAPI, JS (JavaScript) and C/C++ code can access each other.

1 JavaScript, TypeScript, and ArkTS

TypeScript is a typed superset of JavaScript. It supports ES6 syntax and supports object-oriented programming concepts such as classes, interfaces, inheritance, generics, etc. It is a statically-type-checked language that provides type annotations, allowing data-type errors to be caught at the code-compilation stage. At the same time, it extends the syntax of JavaScript, so any existing JavaScript program can work under TypeScript without change. To ensure compatibility, TypeScript needs to be compiled into pure JavaScript by a compiler at the compilation stage to run. TypeScript files have the suffix .ts (.ts, .tsx, .d.ts); JavaScript files are .js.

ArkTS, on the other hand, extends some features on the basis of TypeScript, adding things similar to syntactic sugar and "annotations".

2 .ts and .d.ts Files

A .ts file contains the actual code logic and is used to write the implementation of a TypeScript program. The file contains the definitions and implementations of variables, functions, classes, and other TypeScript code. At compile time, the .ts file is converted into a JavaScript file so it can be executed in a browser or other JavaScript runtime environment. A .d.ts file, on the other hand, is a type declaration file that contains only type code and no specific code implementation. Its file name is usually in the form [module-name].d.ts, where d stands for declaration. It is used to describe the type information of JavaScript code in TypeScript. In short, .ts files are where we write actual business logic, and .d.ts files are where type declarations are provided.

3 Basic Data Types

In the NAPI framework, all parameters — whether the eight data types defined in the ECMAScript standard (Boolean, Null, Undefined, Number, BigInt, String, Symbol, and Object) or the Function type — are uniformly encapsulated as napi_value type. Therefore, you can obtain a Function-type parameter just as you would obtain a parameter of a data type.

Basic data types:

  • napi_env corresponds to NativeEngine; in oh it refers to the relevant context environment of JSNAPI in ArkComplier. Any conversion between napi data types and js data types requires it.
  • napi_value corresponds to NativeValue; in oh it refers to all js data types that ArkComplier can recognize. It has subclasses ArkNativeNumber, ArkNativeString, ArkNativeFunction, etc., corresponding to number, string, function, and other data types in js.
  • napi_callback_info corresponds to NativeCallbackInfo; it is the data type used to store the parameter information passed in from js when registering a callback handle. It is a struct.
  • napi_property_descriptor is the data type used to store a single property.
  • napi_callback corresponds to NativeCallback, i.e. the callback handle mentioned earlier; native code registers it as the callback function for the corresponding js interface.

4 NAPI Object Lifecycle

The NAPI object lifecycle represents the entire process from object creation to release, as shown in the figure below:

When the ArkTS application starts, it loads the NAPI module. During the NAPI module loading process, an object A is created for the application to use. Before the application exits or actively releases object A, object A must always remain "active". The entire process from object A's creation to its release also represents the lifecycle of object A.

NAPI对象生命周期

When calling Node-API, handles of objects in the heap of the underlying virtual machine may be returned in the form of napi_values. These handles must keep the object "alive" until the native code no longer needs them.

5 Synchronous Interfaces and Asynchronous Interfaces

Synchronous interfaces execute in the main thread and may cause UI stutter; asynchronous interfaces execute in a worker thread, avoiding blocking of the main thread.

ConceptSynchronous InterfaceAsynchronous Interface
Execution ThreadMain threadWorker thread
BlockingBlocks the main threadDoes not block the main thread
Use CaseSimple tasksComplex tasks, CPU-intensive tasks
Implementation ComplexitySimpleComplex

The asynchronous interface uses the napi_create_async_work function to create an async work item, and uses the napi_queue_async_work function to add it to the scheduling queue. It processes the asynchronous result in the Complete function, calling the callback function or updating the Promise state.

Part Two: Common NAPI Functions

After learning the basic theory of NAPI, this section introduces several functions that developers frequently use.

1 napi_get_cb_info

Function Description:

napi_get_cb_info is a core function in Node.js N-API. It is mainly used in native plugins (usually written in C/C++) to obtain parameter information, the this object, and other context data passed when calling a JavaScript function. Simply put, it is the core of the interaction between native code and JavaScript.

Function Prototype:

napi_status napi_get_cb_info(napi_env env,
                             napi_callback_info cbinfo,
                             size_t* argc,
                             napi_value* argv,
                             napi_value* this_arg,
                             void** data)

Parameter Description:

ParameterType (C/C++)Direction (for the function)Description
envnapi_envInputThe N-API environment handle, providing the context for function execution.
cbinfonapi_callback_infoInputThe callback info handle, usually passed in by Node.js when calling a native function.
argcsize_t *Input/OutputOn input, indicates the expected number of parameters to obtain; on output, indicates the actual number of parameters received.
argvnapi_value *OutputThe array used to store parameters. If nullptr is passed in, parameters are not copied; only the count is obtained.
this_argnapi_value *OutputUsed to receive the this object in JavaScript.
datavoid **OutputUsed to receive the extra data pointer that may be bound when the function was created.

Usage Example:

#include <node_api.h>

// 准备变量来获取参数和信息
size_t argc = 2; // 我们期望获取2个参数
napi_value argv[2]; // 准备一个数组来存放这两个参数
napi_value this_arg;
void* data;

// 调用 napi_get_cb_info 获取信息
status = napi_get_cb_info(env, info, &argc, argv, &this_arg, &data);
if (status != napi_ok) {
  // 处理错误...
}

2 napi_get_value_string_utf8

Function Description: Extracts a UTF-8-encoded C string from a JavaScript string value. It converts a JavaScript string into a UTF-8-format char array for convenient processing by C/C++ code.

Function Prototype:

napi_status napi_get_value_string_utf8(napi_env env,
                                       napi_value value,
                                       char* buf,
                                       size_t bufsize,
                                       size_t* result);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle, providing the context for function execution
valuenapi_valueInputThe JavaScript string value to be converted
bufchar*OutputPointer to the buffer that stores the result (can be NULL)
bufsizesize_tInputBuffer size (in bytes)
resultsize_t*OutputOptional parameter; receives the actual string length (not including the null terminator)

Usage Example:

napi_value js_string;
// ... 获取 JavaScript 字符串到 js_string ...

// 首先获取所需缓冲区大小
size_t length;
napi_get_value_string_utf8(env, js_string, NULL, 0, &length);

// 分配缓冲区(+1 用于空终止符)
char* buffer = (char*)malloc(length + 1);

// 实际获取字符串内容
napi_get_value_string_utf8(env, js_string, buffer, length + 1, NULL);

// 使用 buffer...
free(buffer);

3 napi_create_function

Function Description: Creates a new JavaScript function object that, when called, executes the specified C/C++ callback function.

Function Prototype:

napi_status napi_create_function(napi_env env,
                                 const char* utf8name,
                                 size_t length,
                                 napi_callback cb,
                                 void* data,
                                 napi_value* result);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
utf8nameconst char*InputFunction name (UTF-8 encoded)
lengthsize_tInputFunction name length (use NAPI_AUTO_LENGTH to auto-calculate)
cbnapi_callbackInputThe native callback function to execute when the JavaScript function is called
datavoid*InputUser data passed to the callback function
resultnapi_value*OutputThe newly created JavaScript function object

Usage Example:

napi_value my_function;
napi_create_function(env, "myFunction", NAPI_AUTO_LENGTH, MyNativeFunction, NULL, &my_function);

4 napi_create_object

Function Description: Creates a new empty JavaScript object.

Function Prototype:

napi_status napi_create_object(napi_env env, napi_value* result);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
resultnapi_value*OutputThe newly created JavaScript object

Usage Example:

napi_value obj;
napi_create_object(env, &obj);

5 napi_create_string_utf8

Function Description: Creates a JavaScript string from a UTF-8-encoded C string.

Function Prototype:

napi_status napi_create_string_utf8(napi_env env,
                                    const char* str,
                                    size_t length,
                                    napi_value* result);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
strconst char*InputUTF-8-encoded C string
lengthsize_tInputString length (use NAPI_AUTO_LENGTH to auto-calculate)
resultnapi_value*OutputThe newly created JavaScript string

Usage Example:

napi_value js_string;
napi_create_string_utf8(env, "Hello World", NAPI_AUTO_LENGTH, &js_string);

6 napi_set_named_property

Function Description: Sets a named property on a JavaScript object.

Function Prototype:

napi_status napi_set_named_property(napi_env env,
                                    napi_value object,
                                    const char* utf8name,
                                    napi_value value);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
objectnapi_valueInputThe JavaScript object on which to set the property
utf8nameconst char*InputProperty name (UTF-8 encoded)
valuenapi_valueInputThe property value to set

Usage Example:

napi_value obj, value;
napi_create_object(env, &obj);
napi_create_string_utf8(env, "test", NAPI_AUTO_LENGTH, &value);
napi_set_named_property(env, obj, "propertyName", value);

7 napi_get_value_double

Function Description: Extracts a C double-precision floating-point value from a JavaScript numeric value.

Function Prototype:

napi_status napi_get_value_double(napi_env env, napi_value value, double* result);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
valuenapi_valueInputJavaScript numeric value
resultdouble*OutputThe extracted double-precision floating-point value

Usage Example:

double number;
napi_get_value_double(env, js_number_value, &number);

8 napi_typeof

Function Description: Determines the type of a JavaScript value.

Function Prototype:

napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
valuenapi_valueInputThe JavaScript value to check
resultnapi_valuetype*OutputThe type of the value (such as napi_number, napi_string, etc.)

Usage Example:

napi_valuetype type;
napi_typeof(env, js_value, &type);
if (type == napi_number) {
    // 处理数字类型
}

9 napi_open_handle_scope / napi_close_handle_scope

Function Description: Manages the lifecycle of napi_value handles to prevent memory leaks.

Function Prototype:

napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result);
napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
resultnapi_handle_scope*OutputThe newly created scope handle
scopenapi_handle_scopeInputThe scope handle to close

Usage Example:

napi_handle_scope scope;
napi_open_handle_scope(env, &scope);
// 在此作用域内创建 napi_value
napi_close_handle_scope(env, scope);

10 napi_throw_error

Function Description: Throws a JavaScript error.

Function Prototype:

napi_status napi_throw_error(napi_env env, const char* code, const char* msg);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
codeconst char*InputError code (can be NULL)
msgconst char*InputError message

Usage Example:

napi_throw_error(env, NULL, "Something went wrong");

11 napi_create_int32

Function Description: Creates a JavaScript number from a C int32_t value.

Function Prototype:

napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
valueint32_tInputC integer value
resultnapi_value*OutputThe newly created JavaScript number

Usage Example:

napi_value js_number;
napi_create_int32(env, 42, &js_number);

12 napi_call_function

Function Description: Calls a JavaScript function.

Function Prototype:

napi_status napi_call_function(napi_env env,
                               napi_value recv,
                               napi_value func,
                               size_t argc,
                               const napi_value* argv,
                               napi_value* result);

Parameter Description:

ParameterTypeDirectionDescription
envnapi_envInputN-API environment handle
recvnapi_valueInputThe this object at function call time
funcnapi_valueInputThe JavaScript function to call
argcsize_tInputNumber of arguments
argvconst napi_value*InputArgument array
resultnapi_value*OutputReturn value of the function call (can be NULL)

Usage Example:

napi_value global, func, args[1], result;
napi_get_global(env, &global);
// 假设 func 是一个 JavaScript 函数
napi_call_function(env, global, func, 1, args, &result);

Part Three: NAPI Development Steps

1. Include the Header File and Implement the C/C++ Function Body

The first step is to include #include "napi/native_api.h" in the C/C++ file, and then implement the C/C++ function body according to normal logic.

#include "napi/native_api.h"

2. Define the Mapping between the NAPI Interface Functions to be Exposed and the Native Functions

To expose C/C++ native functions or properties to JavaScript, the mapping is usually done within the framework-provided function static napi_value Init(napi_env env, napi_value exports).

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {"Init", nullptr, ObjectDectionInit, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"Process", nullptr, ObjectDectionProcess, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"DeInit", nullptr, ObjectDectionDeInit, nullptr, nullptr, nullptr, napi_default, nullptr}};
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

Or use macro definitions:

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        DECLARE_NAPI_FUNCTION("Init", ObjectDectionInit),
        DECLARE_NAPI_FUNCTION("Process", ObjectDectionProcess),
        DECLARE_NAPI_FUNCTION("DeInit", ObjectDectionDeInit)
         };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

This completes the relevant mapping.

3. Establish the Mapping between the Interface and the Module

3.1 Define an napi_module Object

Define an napi_module object, bind the corresponding so to the nm_modname property, and bind the entry function that registers the Module.

/*
 * Napi Module define
 */

static napi_module msLiteModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "mslite_napi",
    .nm_priv = ((void *)0),
    .reserved = {0},
};

After binding, you can use import mslite_napi from 'libmslite_napi.so' on the ETS side.

import mslite_napi from 'libmslite_napi.so'

let resourceManager = context.resourceManager
mslite_napi.Init(resourceManager)
mslite_napi
  .Process(this.modelId, picDesc, buffer)
  .then((value: InferResult) => {
    callback(value.objects)
  })
  .catch((err: BusinessError) => {})
mslite_napi.DeInit()

3.2 Bind the napi_module Object to the System Function RegisterModule

Then pass the napi_module object into the system function RegisterModule:

/*
 * module register
 */
extern "C" __attribute__((constructor)) void RegisterModule(void) {
  MS_LOG(INFO) << "RegisterModule() is called";
  napi_module_register(&g_module);
}

3.3 Execute the Entry Function nm_register_func of napi_module

Generally, in the OH system, the built-in NAPI registration entry function is automatically executed by the Framework, so when we develop NAPI ourselves, we need to call and trigger it ourselves.

4. Define the ETS Interface Description File .d.ts

export const Init: (path: Object) => number
export const Process: (
  modeid: number,
  picDesc: Object,
  buffer: ArrayBuffer,
) => number
export const DeInit: () => number

5. Implement Receiving and Processing of ETS Parameters and Feedback of Results on the Native Side

Because on the ETS side you can consider the data types to be weakly typed; the specific type needs to be parsed by the native side itself.

On the native side, the formal-parameter list of the function passed from the ETS side and the return value are of a fixed type.

5.1 Develop a Synchronous Interface

C developers just need to do the data-conversion work properly.

The parameter objects and function objects passed by the JavaScript call are provided to C in such an abstract type as napi_value. The developer needs to convert them into C data types for computation, and then convert the result back to the napi_value type to return. The NAPI framework provides various api interfaces for users to complete these conversions; these conversion operations are implemented by the JS engine behind the scenes.

static napi_value GetVisitCountSync(napi_env env, napi_callback_info info) {
  /* 根据环境变量获取参数 */
  size_t argc = 2; //参数个数
  napi_value argv[2] = { 0 }; //参数定义

  /* 入参变量获取 */
  napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
  // 获取入参的类型
  napi_valuetype valueType = napi_undefined;
  napi_typeof(env, argv[0], &valueType);

  // 入参值转换为C/C++可以操作的数据类型
  char value[VALUE_BUFFER_SIZE] = { 0 };
  size_t valueLen = 0;
  napi_get_value_string_utf8(env, argv[0], value, VALUE_BUFFER_SIZE, &valueLen);

  // ...... 省略若干业务流程计算步骤

  /* C/C++数据类型转换为JS数据类型并返回 */
  napi_value result = nullptr; // JS字符串对象
  std::string resultStr = "Visit Count = 65535";
  napi_create_string_utf8(env, resultStr.c_str(), resultStr.length(), &result);

  return result; //返回JS对象
}
5.1.1 Function Declaration

Each mapped function must take parameters napi_env env, napi_callback_info cbinfo, and return napi_value. To implement js or ets calls, the NAPI framework needs to solve the following problems: data passing and conversion. The input parameters passed in by js/ets and the returned results need to be converted into data types that C/C++ code can operate on. Therefore, the NAPI framework introduces an intermediate data type to respectively correspond to the types of upper-layer js/ets and C/C++, as well as the methods for operating on the data types.

5.1.2 Get Input Parameters

The function napi_get_cb_info obtains the parameters passed in from JavaScript from the cbinfo parameter.

5.1.3 Convert NAPI Types to C/C++-Recognizable Types

napi_value NapiDemo(napi_env env, napi_callback_info cbinfo)
{
        ...
    char* type = nullptr;
    size_t typeLen = 0;
    napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen);
    NAPI_ASSERT(env, typeLen > 0, "typeLen == 0");
    type = new char[typeLen + 1];
    napi_get_value_string_utf8(env, argv[0], type, typeLen + 1, &typeLen);
        ...
}

5.1.4 Return Value

When C++ has no return value, NapiDemo returns nullptr. The NAPI framework has no nullptr; napi_get_undefined converts nullptr into nullptr napi_undefined.

napi_value NapiDemo(napi_env env, napi_callback_info cbinfo)
{
...
    napi_value result = nullptr;
    napi_get_undefined(env, &result);
    return result;
}
Edit this page on GitHub
Prev
Device Tree Introduction
Next
ArkTS Introduction