|
|
|
|||
|
JNI Programming in C++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(env, "java/lang/String"); The extra level of indirection on The
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 a jobject to GetMethodID because GetMethodID expects a jclass. You can see this by examining the GetMethodID signature:
The C compiler treatsjmethodID GetMethodID(jclass clazz, const char *name, const char *sig); jclass as
the same as jobject because it makes this determination using the following typedef statement:
Therefore a C compiler is not able to detect that you have mistakenly passed the method atypedef jobject jclass; jobject instead of jclass.
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
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 of jobject, which is the
return type of GetObjectArrayElement.
| |||
|