开发者

JNI: How can i check if jobject is a null object in native c code

JNI: How can i check if jobject is a null object in native c cod开发者_开发技巧e


Since the objects in Java and C code actually use the same memory locations (the object passed to the native code is the same memory reference in both worlds), a simple

if (someJObject == NULL) {}

in the C code should be just fine I guess. I haven't tested it though :-)


Stewori's comment deserves to be an answer, so here it is:

(*env)->IsSameObject(env, someJObject, NULL) 

I think that this test succeeds where value comparison fails when the reference type is JNIWeakGlobalRefType, vs a local or a global ref.


The accepted answer and the other answers are all correct. But to be more clear, you can always check

if (someJObject == NULL) {}

for both local and global references.

As for a weak global reference, you should use

(*env)->IsSameObject(env, someJObject, NULL)

because the original object on Java side could be garbage collected already while the someJObject on C side still has the old reference value. So it's safe to say the latter always will work for both cases.

But there's another thing to note here. You shouldn't call any JNI functions based on the result value of IsSameObject(), if it's a weak global reference. This is because the object can be garbage collected anytime, even just after getting TRUE from IsSameObject(). You can get what I mean from here and here.

So, personally I think you may choose whatever you want unless you're dealing with some special cases with weak global references. For simple cases, the former is more easy to read and even cheaper than calling a JNI function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜