Android NDK:从共享库内的资产中读取文件 [英] Android NDK: read file from assets inside of shared library

查看:30
本文介绍了Android NDK:从共享库内的资产中读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我必须将文件从 assets 文件夹传递到 shared library.我现在不能使用 jni 来做到这一点.我在我的项目中使用了预编译的共享库,其中我已经硬编码了我的文件的路径,但是我收到错误 没有这样的文件或目录".所以在我的 .apk 文件中,我在 libs/armeabi-v7a 文件夹中有 .so 文件,在 /assets 中有我的文件em> 文件夹.

In my app I have to pass a file from assets folder to shared library. I cannot do it with use of jni right now. I'm using precompiled shared library in my project, in which I have hardcoded path to my file, but I'm getting error "No such file or directory". So in my .apk file I have .so file in libs/armeabi-v7a folder and my file in /assets folder.

我尝试过这样做:

char *cert_file = "/assets/cacert.cert";
av_strdup(cert_file);

还有其他一些路径,但它不起作用.

And some other paths, but it doesn't work.

有可能吗?

推荐答案

您可以简单地使用 C++ 中的 AAssetManager 类.

You can simply use the AAssetManager class in C++.

基本上你需要:

  • 在你的库初始化期间获得一个指针:AAssetManager*assetManager
  • 用它来读取你的文件:

  • During the init of you library get a pointer on: AAssetManager* assetManager
  • Use it to read your file:

// Open your file
AAsset* file = AAssetManager_open(assetManager, filePath, AASSET_MODE_BUFFER);
// Get the file length
size_t fileLength = AAsset_getLength(file);

// Allocate memory to read your file
char* fileContent = new char[fileLength+1];

// Read your file
AAsset_read(file, fileContent, fileLength);
// For safety you can add a 0 terminating character at the end of your file ...
fileContent[fileLength] = '';

// Do whatever you want with the content of the file

// Free the memoery you allocated earlier
delete [] fileContent;

您可以在此处找到官方 ndk 文档.

获取 AAssetManager 对象:

To get the AAssetManager object:

  • 在原生Activity中,你的main函数作为参数android_app* app,你只需要在这里获取它:app->activity->assetManager
  • 如果你有一个 Java 活动,你需要通过 JNI 发送一个 java 对象 AssetManager 的实例,然后使用函数 AAssetManager_fromJava()
  • In a native activity, you main function as a paramater android_app* app, you just need to get it here: app->activity->assetManager
  • If you have a Java activity, you need so send throught JNI an instance of the java object AssetManager and then use the function AAssetManager_fromJava()

这篇关于Android NDK:从共享库内的资产中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆