简体   繁体   中英

JNI: global reference to a jarray in C++

I'm writing a java program which makes extensive use of native methods and JNI implemented in C++. On the C++ side, I have a local reference to a jarray which I would like to convert to a global reference. Simple, I think: call env->NewGlobalRef(array_ref) . And, indeed, this works --- but the result is a jobject , not a jarray . Is it safe to downcast this back to a jarray ? If not, can I recover a jarray from it? Note that I'm in C++, where these are not just typedefs of each other.

Yes, that should be safe since a jarray is a subtype of jobject [ref] and is basically a pointer. Here's the relevant code from jni.h under the #ifdef __cplusplus part:

class _jobject {};
class _jclass : public _jobject {};
:
:
class _jarray : public _jobject {};
class _jbooleanArray : public _jarray {};
:

typedef _jobject *jobject;
:
typedef _jarray *jarray;
typedef _jbooleanArray *jbooleanArray;
:

As is evident, these are just dummy classes to implement subtyping and jarray and jobject are of type _jobject* and _jarray* and the class _jarray just inherits from _jobject to evince the is-a relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM