Android NDK - using AssetManager in native code

I need to work with assets in my resource folder from C / C ++ code. Is it safe to cache a pointer to AAssetManager like this ...:

AAssetManager* assetMgr = NULL; void Java_com_example_createAssetManager(JNIEnv* env, jclass clazz, jobject assetManager) { AAssetManager* mgr = AAssetManager_fromJava(env, assetManager); assert(NULL != mgr); assetMgr = mgr; } 

... and then use it whenever I need it? CreateAssetManager is called from the Java method onCreate of the main activity (UI thread), but the use in C / C ++ is that when processing the nativly rendering and tick of the game from its own methods in the GLSurfaceView implementation.

1) does assetMgr pointer point to a valid durin object for the entire application? Is it enough to create it just like a static variable on the Java side (in the Activity class), so the garbage collector will not destroy it?

2) is there any danger, will I encounter some problems with threads?

Thanks Tom Atom

+6
source share
2 answers

One of the safest ways to cache Asset Manager is to maintain a global reference to the main Java object on the C side along with the cached pointer AAssetManager . At least with this, you would know that the Java object behind / around the C object will not collect garbage.

To do this, call env->NewGlobalRef(assetManager) .

And access to the asset manager at the flow border will be pretty crazy, IMHO. This is a very strong design constraint - unless explicitly stated, thread safety can never be accepted by default.

+3
source

I wrote an NDK module, Assetbridge , which may also be useful. It exports the contents of your project assets / folders (files and directories) to a temporary directory and then sets the environment variable to this path, so your own code can chdir () in the temp directory and you can use the usual old IO library standard.

+2
source

Source: https://habr.com/ru/post/918484/


All Articles