开发者

Implement JNI listener

开发者 https://www.devze.com 2022-12-22 01:17 出处:网络
I have the following code in a c++ \"listener class\" (more or less), whic开发者_开发知识库h calls some function of a Java object. I suspect there\'s a memory leak:

I have the following code in a c++ "listener class" (more or less), whic开发者_开发知识库h calls some function of a Java object. I suspect there's a memory leak:

JNIEnv *env = NULL;
vm_->AttachCurrentThread(&env, NULL);
const jclass cls = env->FindClass(...);
const jmethodID meth = env->GetMethodID(...);
const jobject obj = env->NewObject(cls, meth, ...);

[ more code ]

env->DeleteLocalRef(obj);

My question is: should I also release the local reference of cls and meth? JNI Documentation isn't very clear about it.


No, there is no need to do so. There is no heap allocated for those two variables, they are only local to the current method and don't have to be free'd or something.

As a rule of thumb, you have to delete JNI objects that were created with a method that has New in it's name, e.g.

env->NewStringUTF(...)
env->NewObjectArray(...)
env->NewObject(...)

because those methods all translate to some kind of memory allocation on the heap (new, malloc)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号