I use NDK to allocate large buffer for Java:
allocNativeBuffer(JNIEnv* env, jobject cls, jlong size) {
void* buffer = malloc(size);
jobject directBuffer = env->NewDirectByteBuffer(buffer, size);
jobject globalRef = env->NewGlobalRef(directBuffer);
return globalRef;
}
After using this buffer I deallocate it:
freeNativeBuffer(JNIEnv* env, jobject cls, jobject globalRef) {
void *buffer = env->GetDirectBufferAddress(globalRef);
env->DeleteGlobalRef(globalRef);
free(buffer);
}
On Android 2.2 it works fine, but on Android 4.0.3 application crashes during DeleteGlobalRef call. What am I doing wrong?
The implementation of global and local references was completely overhauled in ICS, with intention to improve memory management on the Java side. Find the explanation in developers guide Read more in the developers blog.
In the nutshell, whatever you receive in a JNI function, including the
globalRefparameter offreeNativeBuffer()function, are local references. You can create and keep a global reference in your C code, like this:PS I found the stackoverflow discussion which looks like the inspiration for your experiment. See the answer which explains that there was no need to create and delete global references in the first place.