Game Development Reference
In-Depth Information
Loading a Java Class as Global Reference
If you must keep a reference to a Java class (to invoke callbacks when certain events occur,
for example), always use a global reference, as follows:
jclass clazz = (*env)->FindClass(env, "quake/jni/Natives");
jclass globalCls = (jclass)(*env)->NewGlobalRef(env, clazz);
Here you have loaded the Java class quake.jni.Natives and created a global reference
for it. This reference can be used anywhere to invoke C to Java callbacks. You must use
a global reference to prevent the JVM garbage collector from removing the class from
memory. The fact is that you don't know at which point the JVM will decide to get rid of the
class. This is why you need a global reference.
Converting a Java Array to a C array
This can be really helpful if you are sending startup arguments to the native side. Java string
arrays cannot simply be used within C; they must be converted. See the following examples.
jarray :
To get the length of the Java array
(*env)->GetArrayLength(env, jarray);
jarray at position i:
To extract a Java string from the Java array
jstring jrow = (jstring)(*env)->GetObjectArrayElement(env, jarray, i);
jrow into a C string:
To convert the string
const char *row = (*env)->GetStringUTFChars(env, jrow, 0);
Invoking Java Within C (Callbacks)
Remember from the preceding section that the Java class was loaded as a global reference?
Here is where you use it. Callbacks are usually invoked from a different place than JNI functions
(a game loop running in a separate thread, for example). Therefore, it is imperative that you
attach to the current thread before doing any JNI API calls (if you don't, your app may crash).
(*g_VM)->AttachCurrentThread (g_VM, &env, NULL)
OnInitVideo , which has two integer
To load the Java static method
arguments, width and height:
jmethodID mid = (*env)->GetStaticMethodID(env, jNativesCls,
"OnInitVideo", "(II)V");
To invoke the previous method (referenced by mid) using the global
reference to the class loaded in the Global Reference section with
two arguments:
(*env)->CallStaticVoidMethod(env, jNativesCls, mid, width, height);
 
Search WWH ::




Custom Search