HarmonyOS Node-API是基于Node.js 12.x LTS的Node-API规范扩展开发的机制,为开发者提供了ArkTS/JS与C/C++模块之间的交互能力。它提供了一组稳定的、跨平台的API,可以在不同的操作系统上使用。
#include "napi/native_api.h"
static napi_value LoadModule(napi_env env, napi_callback_info info)
{
napi_value result;
// 1. 使用napi_load_module_with_info加载模块
napi_load_module_with_info(env, "entry/src/main/ets/pages/Index", "com.example.callback/entry", &result);
napi_value testFn;
// 2. 使用napi_get_named_property获取test函数
napi_get_named_property(env, result, "test", &testFn);
napi_value inputArgs[2];
int32_t a = 5, b = 4;
napi_create_int32(env, a, &inputArgs[0]);
napi_create_int32(env, b, &inputArgs[1]);
// 3. 使用napi_call_function调用函数test
napi_value output;
napi_call_function(env, result, testFn, 2, inputArgs, &output);
return output;
}
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
{"loadModule", nullptr, LoadModule, nullptr, nullptr, nullptr, napi_default, nullptr}};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
EXTERN_C_END
static napi_module demoModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "entry",
.nm_priv = ((void *)0),
.reserved = {0},
};
extern "C" __attribute__((constructor)) void RegisterEntryModule(void) { napi_module_register(&demoModule); } export const loadModule:()=>any;
import testNapi from 'libentry.so';
export function test(a:number,b:number){
let c = a - b;
console.log("%d - %d = %d", a, b, c);
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.message = 'Welcome';
testNapi.loadModule();
})
}
.width('100%')
}
.height('100%')
}
} # the minimum version of CMake.
cmake_minimum_required(VERSION 3.5.0)
project(S_20250329170715728896)
# 定义一个变量,并赋值为当前模块cpp目录
set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
# 添加头文件.h目录,包括cpp,cpp/include,告诉cmake去这里找到代码引入的头文件
include_directories(${NATIVERENDER_ROOT_PATH}
${NATIVERENDER_ROOT_PATH}/include)
# 声明一个产物libentry.so,SHARED表示产物为动态库,hello.cpp为产物的源代码
add_library(entry SHARED napi_init.cpp)
# 声明产物entry链接时需要的三方库libace_napi.z.so
# 这里直接写三方库的名称是因为它是在ndk中,已在链接寻址路径中,无需额外声明
target_link_libraries(entry PUBLIC libace_napi.z.so)