- 在index.d.ts文件中,提供ArkTS侧的接口方法。
export const nativeCallArkTS: (a: object) => number;
- 实现Native侧的NativeCallArkTS接口,具体代码如下:
static napi_value NativeCallArkTS(napi_env env, napi_callback_info info)
{
size_t argc = 1;
// 声明参数数组
napi_value args[1] = { nullptr };
// 获取传入的参数并依次放入参数数组中
napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
// 创建一个int,作为ArkTS的入参
napi_value argv = nullptr;
napi_create_int32(env, 2, &argv );
// 调用传入的callback,并将其结果返回
napi_value result = nullptr;
napi_call_function(env, nullptr, args[0], 1, &argv, &result);
return result;
}
- 在ArkTS侧,通过nativeModule.nativeCallArkTS()方法传入方法。
entry/src/main/ets/pages/Index.ets
// 通过import的方式,引入Native能力。
import nativeModule from 'libentry.so'
@Entry
@Component
struct InvokeArkTSMethod {
@State message: string = 'Test Node-API nativeCallArkTS result: ';
build() {
Row() {
Column() {
// 调用nativeCallArkTS方法,对应到Native的NativeCallArkTS,在Native调用ArkTS function。
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.message += nativeModule.nativeCallArkTS((a: number) => {
return a * 2;
});
})
}
.width('100%')
}
.height('100%')
}
}