|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The JNI provides a slightly cleaner interface for C++ programmers. Thejni.hfile 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
envand theenvargument toFindClassis 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.hfile also defines a set of dummy C++ classes to enforce the subtyping relationships among different variations ofjobjecttypes: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 */jobjecttoGetMethodIDbecauseGetMethodIDexpects ajclass. You can see this by examining theGetMethodIDsignature:The C compiler treatsjmethodID GetMethodID(jclass clazz, const char *name, const char *sig);jclassas the same asjobjectbecause it makes this determination using the followingtypedefstatement:Therefore a C compiler is not able to detect that you have mistakenly passed the method atypedef jobject jclass;jobjectinstead 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);jstringis a subtype ofjobject, which is the return type ofGetObjectArrayElement.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.