DeleteGlobalRef crash on ICS

爱⌒轻易说出口 提交于 2019-12-23 15:51:03

问题


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?


回答1:


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 globalRef parameter of freeNativeBuffer() function, are local references. You can create and keep a global reference in your C code, like this:

static jobject globalRef;

allocNativeBuffer(JNIEnv* env, jobject cls, jlong size) {
    void* buffer = malloc(size);
    jobject directBuffer = env->NewDirectByteBuffer(buffer, size);
    globalRef = env->NewGlobalRef(directBuffer);
    return directBuffer;
}

freeNativeBuffer(JNIEnv* env, jobject cls, jobject localRef) {
    void *buffer = env->GetDirectBufferAddress(localRef);
    if (buffer == env->GetDirectBufferAddress(globalRef) {
        /* we received the object that we saved */
        env->DeleteGlobalRef(globalRef);
        free(buffer);
    }
}

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.



来源:https://stackoverflow.com/questions/12803493/deleteglobalref-crash-on-ics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!