JNI NewByteArray fuite de mémoire
J'ai une méthode Java qui traitent un bitmap et retourne une Chaîne de caractères.
Lorsque j'appelle cette méthode de JNI (VS 2010), il fonctionne, mais si j'appelle cette méthode plusieurs fois,
la mémoire du processus grandi jusqu'à ce crash.
L'instruction qui utilisent beaucoup de mémoire est:
jbyteArray jBuff = _env->NewByteArray(b->Length);
Mon code:
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));
}
source d'informationauteur Rick
Vous devez vous connecter pour publier un commentaire.
la réponse est:
_env->DeleteLocalRef(jBuff);
Vous n'avez pas d'appel
DetachCurrentThread()
pour chaqueAttachCurrentThread()
qui est demandé dans Java Native Interface Specification. Qui rend les références locales (jBuff
etstr
) l'impossibilité d'être libéré automatiquement. Aussi, leconst char*
récupérés parGetStringUTFChars()
doit être libérée.La bonne façon est de changer
en