鸿蒙5.0开发常见问题【如何在Native侧跨模块访问资源?】

解决措施

可以通过createModuleContext(moduleName)接口创建同应用中不同module的上下文,获取到resourceManager对象后,在Native侧使用Native Rawfile接口操作Rawfile目录和文件来跨模块访问资源。

具体使用方式可参考以下代码:

  1. 在src/main/cpp/CMakeLists.txt文件中,添加依赖资源librawfile.z.so。

    target_link_libraries(nativecrossmoduleaccessres PUBLIC libace_napi.z.so libace_napi.z.so libhilog_ndk.z.so librawfile.z.so)

  2. 在src/main/cpp/types/libentry/index.d.ts文件中,声明应用侧函数getRawFileContent。

import { resourceManager } from "@kit.LocalizationKit"; 
export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array;
  1. 在src/main/cpp/napi_init.cpp文件中实现功能代码。
#include "napi/native_api.h" 
#include <rawfile/raw_file.h> 
#include <rawfile/raw_file_manager.h> 
#include "hilog/log.h" 
 
const int GLOBAL_RESMGR = 0xFF00; 
const char *TAG = "[Sample_rawfile]"; 
namespace { 
    napi_value CreateJsArrayValue(napi_env env, std::unique_ptr<uint8_t[]> &data, long length) 
    { 
        napi_value buffer; 
        napi_status status = napi_create_external_arraybuffer( 
            env, data.get(), length, 
            [](napi_env env, void *data, void *hint) { 
                delete[] static_cast<char *>(data); 
            }, 
            nullptr, &buffer); 
        if (status != napi_ok) { 
            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create external array buffer"); 
            return nullptr; 
        } 
        napi_value result = nullptr; 
        status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result); 
        if (status != napi_ok) { 
            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create media typed array"); 
            return nullptr; 
        } 
        data.release(); 
        return result; 
    } 
} 
static napi_value GetRawFileContent(napi_env env, napi_callback_info info) 
{ 
    OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "GetFileContent Begin"); 
    size_t requireArgc = 3; 
    size_t argc = 2; 
    napi_value argv[2] = { nullptr }; 
    // 获取参数信息 
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); 
    // argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。 
    NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); 
    size_t strSize; 
    char strBuf[256]; 
    napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); 
    std::string filename(strBuf, strSize); 
    // 获取rawfile指针对象 
    RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str()); 
    if (rawFile != nullptr) { 
        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "OH_ResourceManager_OpenRawFile success"); 
    } 
    // 获取rawfile大小并申请内存 
    long len = OH_ResourceManager_GetRawFileSize(rawFile); 
    std::unique_ptr<uint8_t[]> data= std::make_unique<uint8_t[]>(len); 
    // 一次性读取rawfile全部内容 
    int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); 
    // 关闭打开的指针对象 
    OH_ResourceManager_CloseRawFile(rawFile); 
    OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); 
    // 转为js对象 
    return CreateJsArrayValue(env, data, len); 
}
  1. ArkTS侧调用,此处需要传入资源对象。
import testNapi from 'libnativecrossmoduleaccessres.so'; 
 
@Entry 
@Component 
struct Index { 
  @State message: string = 'Native Cross Module Access Resource'; 
  private resMgr = getContext().createModuleContext('NativeAccessRes').resourceManager;  // 获取本应用包的资源对象 
  build() { 
    Row() { 
      Column() { 
        Text(this.message) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
          .onClick(() => { 
            let rawfileContext = testNapi.getRawFileContent(this.resMgr, 'rawfile.txt'); 
            console.log("rawfileContext" + rawfileContext); 
          }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值