基于napi_load_module_with_info实现的napi调用arkts的接口

功能描述

napi_load_module_with_info接口的功能是进行模块的加载,当模块加载出来之后,可以使用函数napi_get_property获取模块导出的变量,也可以使用napi_get_named_property获取模块导出的函数,该函数可以在新创建的ArkTs基础运行时环境中使用

接口介绍

napi_status napi_load_module_with_info(napi_env env,
const char* path,
const char* module_info,
napi_value* result);

参数

说明

env

当前的虚拟机环境

path

加载的文件路径或者模块名

module_info

bundleName/moduleName的路径拼接

result

加载的模块

相关功能接口:

napi_load_module_with_info 获取模块名

napi_get_named_property 获取模块中的函数

napi_call_function 调用函数

napi_load_module_with_info的使用场景

加载本地工程的hap模块的文件路径和har模块名,加载远程包的har模块名和ohpm包名,加载API(@ohos或@system),加载Native库(.so文件)

场景一:加载同模块内自定义ArkTs文件导出内容的同步方法

arkts侧代码:

//./src/main/ets/Test.ets
let value = 123;
function test() {
  console.log("Hello Harmony OS");
}
export {value, test};

build-profile.json5配置:

{
  "buildOption" : {
  "arkOptions" : {
    "runtimeOnly" : {
      "sources": [
      "./src/main/ets/Test.ets"
      ]
    }
  }
}
}

native侧代码:

static napi_value loadModule(napi_env env, napi_callback_info info) {
  napi_value result;
  //1. 使用napi_load_module_with_info加载Test文件中的模块
  napi_status status = napi_load_module_with_info(env, "entry/src/main/ets/Test", "com.example.application/entry", &result);
  ​
  napi_value testFn;
  //2. 使用napi_get_named_property获取test函数
  napi_get_named_property(env, result, "test", &testFn);
  //3. 使用napi_call_function调用函数test
  napi_call_function(env, result, testFn, 0, nullptr, nullptr);
  ​
  napi_value value;
  napi_value key;
  std::string keyStr = "value";
  napi_create_string_utf8(env, keyStr.c_str(), keyStr.size(), &key);
  //4. 使用napi_get_property获取变量value
  napi_get_property(env, result, key, &value);
  return result;
}

场景二:加载同模块内自定义ArkTs文件导出内容的异步方法

与场景一配置相同,在使用napi_load_module_with_info 获取模块名,napi_get_named_property 获取模块中的函数后,可参考线程安全函数:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/use-napi-thread-safety-V5

场景三:加载ohpm包名和har模块名

在基础用法上要在oh-package.json5引入对应的har和包依赖,在build-profile.json5配置对应的名称

oh-package.json5配置:

{
  "dependencies": {
  "library": "file:../library" //本地har
  //"library": "file:./libs/library.har" //远程本地har
  //"json5": "^2.2.3" //ohpm包
}
}

build-profile.json5配置:

{
  "buildOption" : {
  "arkOptions" : {
    "runtimeOnly" : {
      "packages": [
      "library"
      //"json5"
      ]
    }
  }
}
}

native侧代码:

加载har模块

static napi_value loadModule(napi_env env, napi_callback_info info) {
  napi_value result;
  //1. 使用napi_load_module_with_info加载Test文件中的模块
  napi_status status = napi_load_module_with_info(env, "library", "com.example.application/entry", &result);
  ​
  napi_value testFn;
  //2. 使用napi_get_named_property获取test函数
  napi_get_named_property(env, result, "test", &testFn);
  //3. 使用napi_call_function调用函数test
  napi_call_function(env, result, testFn, 0, nullptr, nullptr);
  ​
  napi_value value;
  napi_value key;
  std::string keyStr = "value";
  napi_create_string_utf8(env, keyStr.c_str(), keyStr.size(), &key);
  //4. 使用napi_get_property获取变量value
  napi_get_property(env, result, key, &value);
  return result;
}

加载ohpm包名

static napi_value loadModule(napi_env env, napi_callback_info info) {
  napi_value result;
  //1. 使用napi_load_module_with_info加载json5
  napi_status status = napi_load_module_with_info(env, "json5", "com.example.application/entry", &result);
  ​
  napi_value key;
  std::string keyStr = "default";
  napi_create_string_utf8(env, keyStr.c_str(), keyStr.size(), &key);
  //2. 使用napi_get_property获取default对象
  napi_value defaultValue;
  napi_get_property(env, result, key, &defaultValue);
  ​
  napi_value stringifyFn;
  //3. 使用napi_get_named_property获取stringify函数
  napi_get_named_property(env, defaultValue, "stringify", &stringifyFn);
  //4. 使用napi_call_function调用函数stringify
  napi_value argStr;
  std::string text = "call json5 stringify";
  napi_create_string_utf8(env, text.c_str(), text.size(), &argStr);
  napi_value args[1] = {argStr};
  ​
  napi_value returnValue;
  napi_call_function(env, defaultValue, stringifyFn, 1, args, &returnValue);
  return result;
}

场景四:加载系统API@ohos@system

系统api可直接在native侧调用,无需配置

static napi_value loadModule(napi_env env, napi_callback_info info) {
  //1. 使用napi_load_module_with_info加载模块@ohos.hilog
  napi_value result;
  napi_status status = napi_load_module_with_info(env, "@ohos.hilog", nullptr, &result);
 
  //2. 使用napi_get_named_property获取info函数
  napi_value infoFn;
  napi_get_named_property(env, result, "info", &infoFn);
 
  napi_value tag;
  std::string formatStr = "test";
  napi_create_string_utf8(env, formatStr.c_str(), formatStr.size(), &tag);
 
  napi_value outputString;
  std::string str = "Hello Harmony OS";
  napi_create_string_utf8(env, str.c_str(), str.size(), &outputString);
 
  napi_value flag;
  napi_create_int32(env, 0, &flag);
  ​
  napi_value args[3] = {flag, tag, outputString};
  //3. 使用napi_call_function调用info函数
  napi_call_function(env, result, infoFn, 3, args, nullptr);
  return result;
}

场景五:加载模块Native库(xxx.so

只支持包含index.d.ts的Native模块

.soindex.d.ts代码

export const add: (a: number, b: number) => number;

oh-package.json5配置:

{
  "dependencies": {
  "libentry.so": "file../src/main/cpp/types/libentry"
}
}

build-profile.json5配置:

{
  "buildOption" : {
  "arkOptions" : {
    "runtimeOnly" : {
      "packages": [
      "libentry.so"
      ]
    }
  }
}
}

native侧代码:

static napi_value loadModule(napi_env env, napi_callback_info info) {
  napi_value result;
  //1. 使用napi_load_module_with_info加载libentry.so
  napi_status status = napi_load_module_with_info(env, "libentry.so", "com.example.application/entry", &result);
  ​
  napi_value addFn;
  //2. 使用napi_get_named_property获取add函数
  napi_get_named_property(env, result, "add", &addFn);
 
  napi_value a;
  napi_value b;
  napi_create_int32(env, 2, &a);
  napi_create_int32(env, 3, &b);
  napi_value args[2] = {a, b};
  //3. 使用napi_call_function调用函数add
  napi_value returnValue;
  napi_call_function(env, result, addFn, 2, args, &returnValue);
  return result;
}

场景六:在线程中加载ArkTs运行时环境的自定义模块

通过pthread_create创建新线程后,可以通过napi_create_ark_runtime来创建一个新的ArkTs基础运行时环境,并通过该运行时环境加载ArkTs模块,目前支持在ArkTs模块中使用console接口打印日志,使用timer定时器功能。当使用结束后,需要通过napi_destroy_ark_runtime来销毁所创建的ArkTs基础运行时环境。

arkts侧代码:

// ObjectUtils.ets
export function Logger() {
  console.log("print log");
}

native侧代码:

#include <pthread.h>
​
#include "napi/native_api.h"
​
static void *CreateArkRuntimeFunc(void *arg)
{
  // 1. 创建基础运行环境
  napi_env env;
  napi_status ret = napi_create_ark_runtime(&env);
  if (ret != napi_ok) {
    return nullptr;
  }
  ​
  // 2. 加载自定义模块
  napi_value objUtils;
  ret = napi_load_module_with_info(env, "ets/pages/ObjectUtils", "com.exmaple.myapplication/entry", &objUtils);
  if (ret != napi_ok) {
    return nullptr;
  }
  ​
  // 3. 使用ArtTs中的logger
  napi_value logger;
  ret = napi_get_named_property(env, objUtils, "Logger", &logger);
  if (ret != napi_ok) {
    return nullptr;
  }
  ret = napi_call_function(env, objUtils, logger, 0, nullptr, nullptr);
  ​
  // 4. 销毁arkts环境
  ret = napi_destroy_ark_runtime(&env);
  ​
  return nullptr;
}
​
​
static napi_value CreateArkRuntime(napi_env env, napi_callback_info info)
{
  pthread_t tid;
  pthread_create(&tid, nullptr, CreateArkRuntimeFunc, nullptr);
  pthread_join(tid, nullptr);
  return nullptr;
}

场景七:在har1native侧调用har2ets方法的方法

har1中的代码

arkts侧代码:

export function circleTest(a: string) {
  a = "com.example.loadmoduleinfodemo/entry"
  let libHar:ESObject = napi.napiLoadModule("libraryHar",a);
  console.log(libHar.b);
  libHar.circleTest();
}

build-profile.json5配置:

"buildOption": {
  "arkOptions": {
    "runtimeOnly": {
      "sources": [
      ],
      "packages":  [ 'libraryHar', 'liblibrary.so']//har2,har1的so
    }},
  "externalNativeOptions": {
    "path": "./src/main/cpp/CMakeLists.txt",
    "arguments": "",
    "cppFlags": "",
  }
},

native代码:

static napi_value LoadModule(napi_env env, napi_callback_info info) {
  size_t argc = 2;
  napi_value args[2] = {nullptr};
  ​
  napi_status params = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
  ​
  napi_value path_c = args[1];
  napi_value name_c = args[0];
  char name[500] = {0};
  char path[500] = {0};
  size_t len1 = 0;
  size_t len2 = 0;
  //接收传入的"com.example.loadmoduleinfodemo/entry"路径和"libraryHar"har包名称
  napi_get_value_string_utf8(env, name_c, name, 500, &len1);
  napi_get_value_string_utf8(env, path_c, path, 500, &len2);
  napi_value result;
  //加载har模块
  napi_status status = napi_load_module_with_info(env,  name, path, &result);
 
  napi_value nameFun = nullptr;
  //获取自定义函数
  status = napi_get_named_property(env, result, "circleTest", &nameFun);
  napi_value outputObject;
  //调用函数
  status = napi_call_function(env, nullptr, nameFun, 0, nullptr, &outputObject);
  ​
  OH_LOG_ERROR(LOG_APP, "chenlin LoadModule status %{public}d", status);
  return result;
}

har2中的代码

arkts侧代码:

export { b, c,libHarTest, circleTest } from "./src/main/ets/Test"
export function circleTest() {
  console.log("napi_load_module_with_info static product har function test circle");
}
export let b = "napi_load_module_with_info static product har variable test circle";

 

### 鸿蒙开发中调用接口的方法 鸿蒙(HarmonyOS)作为一款分布式操作系统,提供了丰富的接口以支持开发者进行应用开发。以下将详细介绍几种常见的接口调用方法及其应用场景。 #### 1. AI功能接口调用 在鸿蒙系统中,AI功能接口调用可以通过特定的模块实现。例如,文本转语音(Text To Speech, TTS)和多目标识别(Object Detection)等功能可以借助`@kit.CoreSpeechKit`和`@kit.CoreVisionKit`等模块完成[^4]。以下是调用TTS接口的示例代码: ```typescript import { textToSpeech } from '@kit.CoreSpeechKit'; let tts = textToSpeech.createTTS(); tts.speak("Hello, HarmonyOS!", { language: "en-US", onEvent: (event) => { console.log("TTS Event: " + event); } }); ``` #### 2. 跨进程通信接口(HarmonyOS IDL) 为了实现跨进程通信(IPC),鸿蒙系统引入了HarmonyOS Interface Definition Language(IDL)。通过定义客户端与服务端均认可的编程接口,可以实现在不同进程间的数据共享或方法调用[^2]。以下是一个简单的IDL接口定义示例: ```idl interface IMyService { int add(int a, int b); }; ``` 此接口可以在服务端实现,并在客户端通过代理调用。 #### 3. ArkTS异步接口调用 对于ArkTS环境中的异步接口调用,鸿蒙提供了Node-API扩展接口,如`napi_run_event_loop`和`napi_stop_event_loop`,用于运行和停止事件循环[^3]。以下是一个调用异步接口的示例: ```typescript import { someAsyncFunction } from 'module'; someAsyncFunction().then(result => { console.log("Result:", result); }).catch(error => { console.error("Error:", error); }); ``` #### 4. Native层调用ArkTS/系统接口 在某些场景下,需要从Native层调用ArkTS或系统接口。这可以通过`napi_load_module`函数加载指定的TS/JS模块,并通过`napi_get_named_property`获取导出变量[^5]。以下是一个获取模块导出变量的示例: ```c static napi_value GetNativeModule(napi_env env, const char *modulePath, const char *key) { napi_value module; napi_load_module(env, modulePath, &module); napi_value outputObject = nullptr; napi_get_named_property(env, module, key, &outputObject); return outputObject; } ``` ### 注意事项 - 在调用接口时,需确保已正确导入相关模块并遵循其调用规范。 - 对于跨进程通信,建议设计清晰的接口定义以减少潜在的兼容性问题。 - 异步接口调用时,应妥善处理回调或Promise以避免程序异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值