java - JNI NewByteArray 内存泄漏

标签 java visual-studio-2010 visual-c++ java-native-interface

我有一个处理位图并返回字符串的 Java 方法。 当我从 JNI (VS 2010) 调用此方法时它有效,但如果我多次调用此方法, 进程的内存增长直到崩溃。 占用大量内存的指令是:

jbyteArray jBuff = _env->NewByteArray(b->Length);

我的代码:

static jobject staticArray=0;

System::String^ MyClass::ExecuteJavaMethod(System::Drawing::Bitmap^ bmp)
{
    JNIEnv *_env;
    System::String^ out;
    unsigned const char * buff;

    int res = jvm->AttachCurrentThread((void **)&_env, NULL);

    if (jvm->GetEnv((void**) &_env, JNI_VERSION_1_6) != JNI_OK)
    {
        return "GetEnv ERROR";
    }

    //save the bitmap in the stream
    MemoryStream^ ms = gcnew MemoryStream();
    bmp->Save(ms, ImageFormat::Bmp);

    //get the bitmap buffer
    array<unsigned char>^b = ms->GetBuffer() ;

    //unmanaged conversion
    buff = GetUnmanaged(b,b->Length);


    //fill the buffer
    jbyteArray jBuff = _env->NewByteArray(b->Length);       
    _env->SetByteArrayRegion(jBuff, 0, b->Length, (jbyte*) buff);

    //call the java method
    jstring str = (jstring) _env->CallStaticObjectMethod (  Main,
                                javaMethod,
                                jBuff);



    // _env->ReleaseByteArrayElements(jBuff,(jbyte*)buff), 0); //NOT WORKING

    //staticArray= _env->NewGlobalRef(jBuff);  NOT
    //_env->DeleteLocalRef(jBuff);             WORKING  


    //return the string result of the java method
    return gcnew String(env->GetStringUTFChars(str, 0));

}

最佳答案

答案是:_env->DeleteLocalRef(jBuff);

关于java - JNI NewByteArray 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8574241/

相关文章:

asp.net - 设计师坚持使用 'System.Web.UI.WebControls' ,但该值不存在

visual-c++ - 在MSVC中,为什么InterlockedOr和InterlockedAnd生成循环而不是简单的锁定指令?

c++ - 启动服务器时出现 std::exception (WinSock2)

java - 同步未进入

java - 如何添加 3 个新列?

visual-studio - Visual Studio 2010 中的绿条

.net - DLL中的FileNotFoundException

C++鼠标左键按下帮助

java - 如何使用 JNI 从 C 实现对 Java 的回调?

java - 递归函数StackOverflowError