JNI无法释放内存

问题描述 投票:2回答:1

这是JNI的C ++代码:

extern "C" JNIEXPORT jbyteArray JNICALL
Java_cn_rilled_encoder_JNIEncoder_encodeEncryptBuff(
        JNIEnv* env,
        jobject obj,
        jbyteArray ucInBuffer,
        jintArray unInbufferLen,
        jintArray unOutbufferLen) {

    jbyte *bytes;
    bytes = env->GetByteArrayElements(ucInBuffer, 0);
    int chars_len = env->GetArrayLength(ucInBuffer);
    // chars = new unsigned char[chars_len];
    unsigned char* chars = (unsigned char *) malloc(chars_len);
    memset(chars,0,chars_len);
    memcpy(chars, bytes, chars_len);
    env->ReleaseByteArrayElements(ucInBuffer, bytes, 0);

    int inLength = env->GetArrayLength(unInbufferLen);
    int* inArray = env->GetIntArrayElements(unInbufferLen,0);

    int outLength = env->GetArrayLength(unOutbufferLen);
    int* outArray = env->GetIntArrayElements(unOutbufferLen,0);

    unsigned char* encryptBuff = WCCEncode_Encrypt_Buff(chars, (unsigned int*)inArray, (unsigned int*)outArray);

    jbyteArray bArray=env->NewByteArray(*outArray);

    env->SetByteArrayRegion(bArray, 0, *outArray, (jbyte *)encryptBuff);
    //env->DeleteLocalRef(bArray);
    //env->ReleaseByteArrayElements(bArray, (jbyte *)encryptBuff, 0);
    env->ReleaseIntArrayElements(unInbufferLen, inArray, NULL);
    env->ReleaseIntArrayElements(unOutbufferLen, outArray, NULL);
    free(chars);

    return bArray;
}

这是JNI的Java代码:

public class JNIEncoder {

    static {
        System.loadLibrary("native-lib");
    }

    public static native byte[] encodeEncryptBuff(byte[] ucInBuffer, int[] unInbufferLen, int[] unOutbufferLen);

}

在java线程中调用它:

byte[] result = JNIEncoder.encodeEncryptBuff(content, new int[]{content.length}, outLength);

内存使用情况:

memory usage

释放字符后的内存使用情况:

enter image description here

java android android-ndk jvm java-native-interface
1个回答
0
投票

我用delete encryptBuff解决了这个问题。

New Code

...
unsigned char* chars = (unsigned char *) malloc(chars_len);
...
free(chars);
delete encryptBuff;

return bArray;

新内存使用情况:

new memory usage

© www.soinside.com 2019 - 2024. All rights reserved.