基于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";

 

<think>我们已知用户的问题是关于napi_has_named_property函数的用法。根据引用中提供的信息,我们可以推断该函数用于检查一个对象是否具有指定名称的属性。由于引用中没有直接提到napi_has_named_property,但提到了类似的函数如napi_get_named_property(用于获取命名属性),我们可以类比其使用方式。 函数原型(根据Node.js N-API的常见形式)可能为: napi_status napi_has_named_property(napi_env env, napi_value object, const char* utf8name, bool* result); 参数说明: - env: 表示当前的napi环境。 - object: 要检查的JavaScript对象(napi_value类型)。 - utf8name: 属性名称(以UTF-8编码的字符串)。 - result: 指向布尔值的指针,用于存储检查结果(true表示存在,false表示不存在)。 使用步骤: 1. 准备一个napi_value对象(可以是任何JavaScript对象,例如模块导出对象)。 2. 指定要检查的属性名(字符串)。 3. 调用napi_has_named_property函数,传入环境、对象、属性名和一个布尔变量的地址。 4. 检查函数返回的状态(napi_status)以确保调用成功。 5. 根据布尔变量的值判断属性是否存在。 示例场景: 假设我们有一个ArkTS模块导出的对象,我们想检查该对象是否导出了某个特定的属性(例如,检查是否导出了名为"test"的函数)。 示例代码(基于引用[2]中的场景): 在引用[2]的示例中,我们加载了一个模块,并获取了模块导出的对象(result)。我们可以使用napi_has_named_property来检查该对象是否有某个属性。 注意:由于我们没有直接看到napi_has_named_property在引用中的示例,以下代码是根据N-API的常见用法编写的。 示例代码: ```c static napi_value checkProperty(napi_env env, napi_callback_info info) { napi_value result; // 假设我们已经通过napi_load_module加载了模块,并得到了模块导出对象result // ... 加载模块的代码(参考引用[2]) // 检查模块导出对象中是否有名为"test"的属性 bool hasTest = false; napi_status status = napi_has_named_property(env, result, "test", &hasTest); if (status != napi_ok) { // 错误处理 napi_throw_error(env, NULL, "Failed to check property"); return nullptr; } // 根据hasTest的值进行后续操作 // 例如,我们可以打印一条消息 napi_value returnValue; if (hasTest) { napi_create_string_utf8(env, "Property 'test' exists", NAPI_AUTO_LENGTH, &returnValue); } else { napi_create_string_utf8(env, "Property 'test' does not exist", NAPI_AUTO_LENGTH, &returnValue); } return returnValue; } ``` 注意事项: - 该函数是同步的。 - 属性名必须是UTF-8编码的字符串。 - 在调用该函数之前,确保传入的对象是一个有效的JavaScript对象(非null或undefined)。 如果用户需要更详细的官方文档,建议参考OpenHarmony的N-API文档或Node.js的N-API文档(因为两者在API设计上相似)。 相关问题: 1. napi_has_named_property和napi_has_property有什么区别? 2. 如何遍历一个对象的所有属性? 3. 除了napi_has_named_property,还有哪些常用的属性操作函数? </think>### napi_has_named_property 函数用法详解 `napi_has_named_property` 是 Node-API 中用于检查对象是否包含指定名称属性的函数,其核心作用是**同步验证某个 JavaScript 对象是否拥有特定名称的属性或方法**。以下是详细使用方法: #### 函数原型 ```c napi_status napi_has_named_property( napi_env env, // [in] N-API 环境句柄 napi_value object, // [in] 待检查的 JavaScript 对象 const char* utf8name, // [in] 属性名称(UTF-8 字符串) bool* result // [out] 检查结果(true/false) ); ``` #### 使用步骤 1. **准备参数**: - `env`:当前 N-API 环境句柄(通常从函数参数获取) - `object`:目标 JavaScript 对象(如模块导出对象) - `utf8name`:要检查的属性名称(如 `"test"`) - `result`:存储结果的布尔变量指针 2. **调用函数**: ```c bool has_property; napi_status status = napi_has_named_property( env, export_object, "targetProperty", &has_property ); ``` 3. **处理结果**: ```c if (status != napi_ok) { // 错误处理 } if (has_property) { // 属性存在时的操作 } else { // 属性不存在时的操作 } ``` #### 完整示例 ```c static napi_value CheckProperty(napi_env env, napi_callback_info info) { napi_value export_obj; // 加载模块(参考引用[2]) napi_load_module(env, "ets/Test", &export_obj); // 检查是否存在 "test" 方法 bool has_test; napi_status status = napi_has_named_property(env, export_obj, "test", &has_test); if (status != napi_ok) { napi_throw_error(env, NULL, "Property check failed"); return NULL; } // 返回检查结果 napi_value result; napi_get_boolean(env, has_test, &result); return result; } ``` #### 关键说明 1. **同步操作**:函数立即返回检查结果,无需异步处理 2. **命名属性检查**:仅验证直接属性(不包括原型链) 3. **错误处理**: - 返回 `napi_invalid_arg` 如果参数无效 - 返回 `napi_object_expected` 如果 `object` 不是 JS 对象 4. **典型应用场景**: - 验证模块导出接口完整性 - 条件性调用对象方法(避免未定义错误) - 动态检测运行时对象结构 > 注:该函数常与 `napi_get_named_property`(引用[1])配合使用,实现"检查→获取"的安全操作流[^1][^2]。 #### 注意事项 - 属性名需为 **UTF-8 编码**的 C 字符串 - 对函数/变量均适用(如检查导出函数 `"test"` 或变量 `"value"`) - 当对象为 `null` 或 `undefined` 时将返回错误 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值