Previous | Next | Trail Map | Using the JNI to Integrate Native Code and Java Programs | Java Native Interface Programming


JNI Programming in C++

The JNI provides a slightly cleaner interface for C++ programmers. The jni.h file contains a set of inline C++ functions so that the native method programmer can simply write:
jclass cls = env->FindClass("java/lang/String");
instead of:
jclass cls = (*env)->FindClass(env, "java/lang/String");

The extra level of indirection on env and the env argument to FindClass are hidden from the programmer. The C++ compiler simply expands out the C++ member function calls to their C counterparts; therefore, the resulting code is exactly the same.

The jni.h file also defines a set of dummy C++ classes to enforce the subtyping relationships among different variations of jobject types:

class _jobject {};
class _jclass : public _jobject {};
class _jthrowable : public _jobject {};
class _jstring : public _jobject {};
... /* more on jarray */

typedef _jobject *jobject;
typedef _jclass *jclass;
typedef _jthrowable *jthrowable;
typedef _jstring *jstring;
... /* more on jarray */
The C++ compiler is therefore able to detect if you pass in, for example, a jobject to GetMethodID:
jmethodID GetMethodID(jclass clazz, const char *name,
                      const char *sig);
because GetMethodID expects a jclass. In C, jclass is simply the same as jobject:
typedef jobject jclass;
Therefore a C compiler is not able to detect that you have mistakenly passed a jobject instead of jclass.

The added type safety in C++ does come which a small inconvenience. Recall from Accessing Java Arrays that in C, you can fetch a Java string from an array of strings and directly assign the result to a jstring:

jstring jstr = (*env)->GetObjectArrayElement(env, arr, i);
In C++, however, you need to insert an explicit conversion:
jstring jstr = (jstring)env->GetObjectArrayElement(arr, i);
because jstring is a subtype of jobject, the return type of GetObjectArrayElement.


Previous | Next | Trail Map | Using the JNI to Integrate Native Code and Java Programs | Java Native Interface Programming