Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android NDK - using AssetManager in native code

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

like image 222
Tom Atom Avatar asked Jun 19 '12 14:06

Tom Atom


2 Answers

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.

like image 177
Seva Alekseyev Avatar answered Oct 11 '22 05:10

Seva Alekseyev


I've written an NDK module, Assetbridge, that you might also find useful. It exports the contents of your project's assets/ folder (files and directories) to a temporary directory, and then sets an environment variable to that path, so your native code can chdir() to the temp directory and you can use the regular old standard library file IO routines.

like image 34
Steve H. Avatar answered Oct 11 '22 06:10

Steve H.