what is global about the clsStr variable which is “clsStr = (*env)->NewGlobalRef(env,cls)”?

对着背影说爱祢 提交于 2020-01-25 00:24:07

问题


Global Reference in JNI is said to be a reference that has to be manually freed by the programmer. It has nothing to do with the c context. so a code like :

{
    jclass clsStr = (*env)->NewGlobalRef(env,cls); 
}

return clsStr;

will give an error saying that clsStr is undefined / undeclared. I understand this. But what i don't understand is the use of these type of references.

What is global about clsStr in the above code ? How this variable can be useful in future or after the call returns ? I also read that "Basically, the global reference is useful for ensuring that it (and its contents) will survive to the next JNI invocation" but i don't understand this.


回答1:


It means that you're allowed to hold on to the reference you get from NewGlobalRef() across multiple calls to the native mathod. The reference will remain valid until you explicitly call DeleteGlobalRef().

This is in contrast to local references:

A local reference is valid only within the dynamic context of the native method that creates it, and only within that one invocation of the native method. All local references created during the execution of a native method will be freed once the native method returns.

If you store a global reference in a variable that's allowed to go out of scope before you call DeleteGlobalRef(), you leak memory. The following is an example of that:

{
    jclass clsStr = (*env)->NewGlobalRef(env,cls); 
}



回答2:


Global Reference in JNI is said to be a reference that has to be manually freed by the programmer. It has nothing to do with the c context.

No it isn't. That is a terrible misquote from the JNI Specification. Here's what it really says:

The JNI divides object references used by the native code into two categories: local and global references. Local references are valid for the duration of a native method call, and are automatically freed after the native method returns. Global references remain valid until they are explicitly freed.

Nothing in JNI can alter the semantics of the C programming language.



来源:https://stackoverflow.com/questions/10597968/what-is-global-about-the-clsstr-variable-which-is-clsstr-env-newglobalref

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