Android NDK - using AssetManager in native code

android, android-assets, android-ndk, thread-safety

Solution

One marginally safer way to cache the asset manager would be to hold a global reference to the underlying Java object on the C side along with the cached `AAssetManager` pointer. At least with that you'd know that the Java object behind/around the C object won't be garbage collected.

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

And accessing the asset manager across thread boundary would be rather crazy, IMHO. That's a very strong design constraint - unless documented explicitly, thread safety can never be assumed by default.

Problem

I need to work with assets in my assets folder from within C/C++ code. Is it safe to cache 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 to use it whenever I need it? The createAssetManager is called from Java onCreate method of main Activity (UI thread) but the usage in C/C++ is when nativly processing rendering and game tick called from native methods in GLSurfaceView implementation. 1) will the assetMgr pointer point to valid object durin whole app lifetime? Is it enough to create it also like static variable on Java side (in Activity class) so garbage collector will not destroy it? 2) is there some danger I will run into some problems with threads? Thanks, Tom Atom

Original source