如何在Native侧访问应用包内Rawfile资源
=========================

**解决措施**

使用Native Rawfile接口操作Rawfile目录和文件，可以访问应用包内的资源。

参考以下代码。

1.  在src/main/cpp/CMakeLists.txt文件中，添加依赖资源librawfile.z.so。
    
    target\_link\_libraries(nativeaccessres PUBLIC libace\_napi.z.so libhilog\_ndk.z.so librawfile.z.so)
    
2.  在index.d.ts文件中声明getRawFileContent。
    
    import { resourceManager } from "@kit.LocalizationKit";
    export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array;
    
3.  在napi\_init.cpp文件中实现功能代码。
    
    #include <memory>
    #include "string"
    #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 };
        // Obtain parameter information
        napi\_get\_cb\_info(env, info, &argc, argv, nullptr, nullptr);
    
        // Argv \[0\] is the first parameter of the function, Js resource object, and OH\_ ResourceManagerial is converted to a Native object.
        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);
    
        // Get rawfile pointer object
        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");
        }
        // Get rawfile size and request memory
        long len = OH\_ResourceManager\_GetRawFileSize(rawFile);
        std::unique\_ptr<uint8\_t\[\]> data= std::make\_unique<uint8\_t\[\]>(len);
    
        // Read all contents of rawfile at once
        int res = OH\_ResourceManager\_ReadRawFile(rawFile, data.get(), len);
    
        // Close open pointer objects
        OH\_ResourceManager\_CloseRawFile(rawFile);
        OH\_ResourceManager\_ReleaseNativeResourceManager(mNativeResMgr);
        // Convert to JS object
        return CreateJsArrayValue(env, data, len);
    }
    
4.  在ArkTS侧调用时，需要传入资源对象。
    
    import testNapi from 'libnativeaccessres.so'  // Import so
    
    @Entry
    @Component
    struct Index {
      @State message: string = 'Native Access Resource';
      private resMgr = this.getUIContext().getHostContext()!.resourceManager;  // Retrieve the resource objects of this application package
      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%')
      }
    }
    

参考链接

[Rawfile开发指导](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/rawfile-guidelines)