Android NDK:为什么AAssetManager_open返回NULL [英] Android NDK: Why is AAssetManager_open returning NULL

查看:658
本文介绍了Android NDK:为什么AAssetManager_open返回NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码:

AAsset* pAsset = AAssetManager_open(pAssetManager, "asset_test.txt", AASSET_MODE_STREAMING);
DebugPrint(pAsset?"pAsset not NULL\n":"pAsset NULL");
if (pAsset)
{
    char buf[1024];
    AAsset_read(pAsset, buf, sizeof(buf));
    DebugPrint(buf);
    AAsset_close(pAsset);
}

此代码始终在logcat中打印"pAsset NULL".

This code always prints "pAsset NULL" in logcat.

我将asset_test.txt文件放在资产目录中,然后通过将.apk重命名为.zip并使用7zip打开它来查看.apk,以确保该文件存在.

I put the asset_test.txt file in my assets directory, and I looked in the .apk to make sure it exists by renaming the .apk to .zip and opening it with 7zip.

我还有更多代码:

AAssetDir* pAssetDir = AAssetManager_openDir(pAssetManager, sDirectory.c_str());

if (!pAssetDir)
{
    DebugPrint("pAssetDir NULL\n");
    return;
}

const char* pszDir;
while ((pszDir = AAssetDir_getNextFileName(pAssetDir)) != NULL)
{
    DebugPrint(pszDir);
}

AAssetDir_close(pAssetDir);

此代码不打印任何内容.换句话说,无论我通过什么路径进入资产目录,都找不到文件.

This code prints nothing. In other words, no files are ever found in the assets directory, regardless of what paths I pass into it.

注意:DebugPrint只是围绕__android_log_print()的漂亮包装.

Note: DebugPrint is just a prettier looking wrapper around __android_log_print().

推荐答案

我应该将Activity传递给AAssetManager_fromJava(),而应该将AssetManager传递给我.如果将错误的类传递给AAssetManager_fromJava(),它将失败而无法打印任何需要记录的东西.

I passed the Activity into AAssetManager_fromJava(), while I should have passed the AssetManager in. If you pass the wrong class into AAssetManager_fromJava() it will fail without printing anything to logcat.

如何使用JNI获取资产管理器:

How to get the asset manager with JNI:

    JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();

    jobject activity = (jobject)SDL_AndroidGetActivity();

    jclass activity_class = env->GetObjectClass(activity);

    jmethodID activity_class_getAssets = env->GetMethodID(activity_class, "getAssets", "()Landroid/content/res/AssetManager;");
    jobject asset_manager = env->CallObjectMethod(activity, activity_class_getAssets); // activity.getAssets();
    global_asset_manager = env->NewGlobalRef(asset_manager);

    pAssetManager = AAssetManager_fromJava(env, global_asset_manager);

从现在开始将资产管理器指针存放在某个地方,并将其用于所有AAssetManager _ *()函数.

Stash that asset manager pointer somewhere and use it for all your AAssetManager_*() functions from now on.

这篇关于Android NDK:为什么AAssetManager_open返回NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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