HarmonyOS鸿蒙Next中JS侧拿到rawfile路径传递给CPP并在CPP中读取dat文件的解决方案

HarmonyOS鸿蒙Next中JS侧拿到rawfile路径传递给CPP并在CPP中读取dat文件的解决方案 依赖的so中需要读取工程中的一个.dat资源

4 回复

采用线程安全函数方案,在非UI主线程中调用线程安全函数,回到主线程中执行操作。

1、UI 主线程中获取并保存资源文件对象;

2、创建线程安全函数;

3、在非UI主线程中调用线程安全函数;

4、在线程安全函数中,读取rawfile下的文件资源。

更多关于HarmonyOS鸿蒙Next中JS侧拿到rawfile路径传递给CPP并在CPP中读取dat文件的解决方案的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,JS侧可以通过@ohos.resourceManager模块获取rawfile路径。使用getRawFileContent方法可以获取rawfile的内容,但若需将路径传递给CPP侧,则可以通过@ohos.napi模块调用CPP的Native API。

在JS侧,首先获取rawfile路径,然后通过napi调用CPP函数,将路径作为参数传递。CPP侧使用napi接收路径参数后,可以通过标准C++文件操作函数(如std::ifstream)读取dat文件内容。

示例代码如下:

JS侧:

import resMgr from '@ohos.resourceManager';
import napi from '@ohos.napi';

// 获取rawfile路径
let context = ...; // 获取上下文
let resourceMgr = resMgr.getResourceManager(context);
let rawfilePath = resourceMgr.getRawFile('example.dat');

// 调用CPP函数
napi.callNativeFunction('readDatFile', rawfilePath);

CPP侧:

#include <fstream>
#include <string>
#include <napi.h>

void readDatFile(const Napi::CallbackInfo& info) {
    Napi::Env env = info.Env();
    std::string filePath = info[0].As<Napi::String>().Utf8Value();

    std::ifstream file(filePath, std::ios::binary);
    if (file.is_open()) {
        // 读取文件内容
        std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
        file.close();
        // 处理文件内容
    }
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
    exports.Set("readDatFile", Napi::Function::New(env, readDatFile));
    return exports;
}

NODE_API_MODULE(addon, Init)

此方案实现了JS侧将rawfile路径传递给CPP侧,并在CPP侧读取dat文件的功能。

在HarmonyOS鸿蒙Next中,JS侧可以通过getContext().resourceManager获取rawfile路径,然后通过Native API将路径传递给C++。C++侧可以使用std::ifstreamfopen读取dat文件。具体步骤如下:

  1. JS侧获取路径

    let path = getContext().resourceManager.getRawFileEntry("example.dat").path;
    
  2. JS调用C++接口

    nativeModule.readDatFile(path);
    
  3. C++侧读取文件

    void ReadDatFile(const std::string& path) {
        std::ifstream file(path, std::ios::binary);
        if (file.is_open()) {
            // 读取文件内容
            file.close();
        }
    }
    

确保在CMakeLists.txt中正确配置Native模块,并在config.json中声明相关权限。

回到顶部