OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the [ace_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository are used to implement interaction with JS. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see **libnapi.ndk.json** in the ace_napi repository.
In OpenHarmony, you can use the N-APIs in C APIs to implement interaction between ArkTS/TS/JS and C/C++. The N-API names are the same as those in the third-party **Node.js**. Currently, OpenHarmony supports some N-APIs. For details about the APIs supported, see [arkui_napi](https://gitee.com/openharmony/arkui_napi/blob/master/libnapi.ndk.json).
## How to Develop
The DevEco Studio has a default project that uses NAPIs. You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can import the native .so that contains the JS processing logic. For example, **import hello from 'libhello.so'** to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the **hello** object of the application to call the native capability.
## Development Guidelines
### Registration
* Add **static** to the **nm_register_func** function to prevent symbol conflicts with other .so files.
* The name of the module registration entry, that is, the function decorated by **\_\_attribute\_\_((constructor))**, must be unique.
### .so Naming Rules
The .so file names must comply with the following rules:
* Each module has a .so file.
* The **nm_modname** field in **napi_module** must be the same as the module name. For example, if the module name is **hello**, name the .so file **libhello.so**. The sample code for importing the .so file is **import hello from 'libhello.so'**.
### JS Objects and Threads
The Ark engine prevents NAPIs from being called to operate JS objects in non-JS threads. Otherwise, the application will crash. Observe the following rules:
* The NAPIs can be used only in JS threads.
***env** is bound to a thread and cannot be used across threads. The JS object created by a NAPI can be used only in the thread, in which the object is created, that is, the JS object is bound to the **env** of the thread.
### Importing Header Files
Before using NAPI objects and methods, include **napi/native_api.h**. Otherwise, if only the third-party library header file is included, an error will be reporting, indicating that the interface cannot be found.
### napi_create_async_work
**napi_create_async_work** has two callbacks:
***execute**: processes service logic asynchronously. This callback is not executed by a JS thread; therefore, it cannot call any NAPI. The return value of **execute** is processed by the **complete** callback.
***complete**: calls the NAPI to encapsulate the return value of **execute** into a JS object and return it for processing. This callback is executed by a JS thread.
```c++
napi_statusnapi_create_async_work(napi_envenv,
napi_valueasync_resource,
napi_valueasync_resource_name,
napi_async_execute_callbackexecute,
napi_async_complete_callbackcomplete,
void*data,
napi_async_work*result)
```
The DevEco Studio provides a default project that uses N-APIs. You can choose **File** > **New** > **Create Project** to create a Native C++ project. After the project is created, the **cpp** directory is generated in the **entry/src/main** directory. You can use the N-APIs to develop C/C++ code (native code).
You can import the native .so file for ArkTS/TS/JS programming. For example, you can **import hello from 'libhello.so'** to use the **libhello.so** capability and pass the ArkTS/TS/JS object named **hello** to the ArkTS/TS/JS APIs of the application. You can use this object to invoke the N-APIs in **cpp**.
## Basic Features
The N-APIs implement interaction between ArkTS/TS/JS and C/C++. The following provides two **HelloWorld** project examples:
1. Define an N-API method **Add()**, which is called by ArkTS with two numbers passed in. The N-API **Add**() method adds the two numbers and returns the result to ArkTS.
2. Define an N-API method named **NativeCallArkTS**, which is called by ArkTS with an ArkTS function passed in. The **NativeCallArkTS** method invokes this ArkTS function and returns the result to ArkTS.
## Encapsulating Synchronous and Asynchronous APIs for the Storage Module
The following describes:
1. How an ArkTS method invokes a C++ method.
2. How a C++ method invokes an ArkTS method.
### Overview
The project has the following files:
-**entry\src\main\cpp\hello.cpp**: contains the N-API logic.
-**entry\src\main\ets\pages\index.ets**: contains the ArkTS logic.
-**entry\src\main\cpp\types\libentry\index.d.ts**: contains the declaration of the N-APIs exposed to ArkTS.
This example shows how to encapsulate the synchronous and asynchronous APIs of the **Storage** module. The **Storage** module implements the functions of storing, obtaining, deleting, and clearing data.
The following provides the comments for the files. Other parts in the project are the same as those in the native default project.
You can obtain the complete code from sample/native_module_storage/ in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
**1. Register the module.**
Register four synchronous APIs (**getSync**, **setSync**, **removeSync**, and **clearSync**) and four asynchronous APIs (**get**, **set**, **remove**, and **clear**).
The **getSync** function registered for the **Storage** module is **JSStorageGetSync**. Obtain data from **gKeyValueStorage**, create a string object, and return the object created.
// Number of parameters to be obtained from ArkTS. napi_value can be regarded as the representation of the ArkTS value in the N-API method.
size_t argc = 2;
napi_value args[2] = {nullptr};
// From info(), obtain the parameters passed from ArkTS. In this example, two ArkTS parameters, arg[0] and arg[1], are obtained.
// Convert the obtained ArkTS parameters to the type that can be processed by N-API. In this example, the two numbers passed from ArkTS are converted to the double type.
double value0;
napi_get_value_double(env, args[0], &value0);
// Service logic for obtaining data. This example simply obtains data from a global variable.
autoitr=gKeyValueStorage.find(key);
napi_valueresult=nullptr;
if(itr!=gKeyValueStorage.end()){
// Use the data obtained to create a JS object of the string type.
// Callback 1: This callback contains the service logic to be asynchronously executed and is asynchronously executed by the NAPI. Do not operate JS objects using the NAPI because the execution is asynchronous.
## Binding Native and JS Objects for the NetServer Module
### Overview
This example shows how to implement the **on**, **off**, and **once** methods and bind C++ and JS objects using **wrap()**. The **NetServer** module implements the network service.
You can obtain the complete code from **sample/native_module_netserver/** in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
// Init() hooks native methods, such as Add and NativeCallArkTS, in exports. exports is the ArkTS object obtained after you import the native capabilities.
netServer.start(1000);// The port number is 1000. After start is executed, invoke the start callback registered.
}
}
```js
// entry\src\main\cpp\types\libentry\index.d.ts
// Declare the N-APIs exposed to ArkTS.
exportconstadd:(a:number,b:number)=>number;
exportconstnativeCallArkTS:(a:object)=>number;
```
## Development Guidelines
### Registration
## Calling Back a JS API in a Non-JS Thread
### Overview
This example describes how to invoke a JS callback in a non-JS thread. For example, a sensor listener is registered for a JS application. The sensor data is reported by an SA. When the SA invokes the client through Inter-Process Communication (IPC), the execution thread is an IPC thread, which is different from the JS thread of the SA. In this case, the JS callback must be thrown to the JS thread to execute. Otherwise, the application will crash.
### Implementation
You can obtain the complete code from **sample/native_module_callback/** in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
**2. Obtain the loop in env and throw the task to a JS thread.**
```c++
#include <thread>
* To prevent conflicts with symbols in the .so file, add "static" to the function (such as the Init function) corresponding to **nm_register_func**.
* The entry of module registration, that is, the function name modified by **\_\_attribute\_\_((constructor))** (for example, the **RegisterHelloModule** function), must be unique.
#include "napi/native_api.h"
#include "napi/native_node_api.h"
### .so Naming Rules
#include "uv.h"
The .so file names must comply with the following rules:
structCallbackContext{
napi_envenv=nullptr;
napi_refcallbackRef=nullptr;
intretData=0;
};
* Each module has a .so file.
* The **nm_modname** field in **napi_module** must be the same as the module name. For example, if the module name is **hello**, name the .so file **libhello.so**. The sample code for importing the .so file is **import hello from 'libhello.so'**.
voidcallbackTest(CallbackContext*context)
{
uv_loop_s*loop=nullptr;
// Save the env when the JS callback is registered. Obtain the loop of the JS thread from env.
napi_get_uv_event_loop(context->env,&loop);
// Create uv_work_t to transfer private data (int type 1 in this example). Note that memory must be released after the callback is complete. The logic for generating the returned data is omitted here.
uv_work_t*work=newuv_work_t;
context->retData=1;
work->data=(void*)context;
// Call the libuv API to throw the JS task to the loop for execution.
uv_queue_work(
loop,
work,
// This callback is executed in another common thread to process tasks asynchronously. After the callback is complete, execute the next callback. In this scenario, this callback does not need to execute any task.
[](uv_work_t*work){},
// This callback is executed in the JS thread bound to env.
// Simulate the logic for throwing a task to a non-JS thread.
std::threadtestThread(callbackTest,asyncContext);
testThread.detach();
returnnullptr;
}
```
The ArkCompiler protects JS object threads. Improper use may cause an application crash. Observe the following rules:
**JS Sample Code**
* The N-APIs can be used only by JS threads.
***env** is bound to a thread and cannot be used across threads. The JS object created by an N-API can be used only in the thread, in which the object is created, that is, the JS object is bound to the **env** of the thread.
```js
importcallbackfrom'libcallback.so';
### Header File Import
exportdefault{
testcallback(){
callback.test((data)=>{
console.error('test result = '+data)
})
}
}
```
Import **napi/native_api.h**. Otherwise, an error indicating that the N-API cannot be found will be reported.