Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The JNI provides a slightly cleaner interface for C++ programmers. Thejni.h
file contains a set of inline C++ functions. This allows the native method programmer to simply write:instead of:jclass cls = env->FindClass("java/lang/String");jclass cls = (*env)->FindClass(env, "java/lang/String");The extra level of indirection on
env
and theenv
argument toFindClass
is 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 ofjobject
types:The C++ compiler is therefore better able than the C compiler to detect when incorrect types are passed to methods. For example, it is incorrect to pass aclass _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 */jobject
toGetMethodID
becauseGetMethodID
expects ajclass
. You can see this by examining theGetMethodID
signature:The C compiler treatsjmethodID GetMethodID(jclass clazz, const char *name, const char *sig);jclass
as the same asjobject
because it makes this determination using the followingtypedef
statement:Therefore a C compiler is not able to detect that you have mistakenly passed the method atypedef jobject jclass;jobject
instead ofjclass
.The added type safety in C++ comes with 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
, as follows:In C++, however, you need to insert an explicit conversion of the Java string tojstring jstr = (*env)->GetObjectArrayElement(env, arr, i);jstring
:You must make this explicit conversion becausejstring jstr = (jstring)env->GetObjectArrayElement(arr, i);jstring
is a subtype ofjobject
, which is the return type ofGetObjectArrayElement
.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.