Game Development Reference
In-Depth Information
Initializing the Game Loop
This is the most important function in this file. It starts the native game loop and will block execution.
For this reason, this function should be called within a Java thread. The critical steps shown in Listing 6-15
follow:
1.
Save a reference to the Java VM is using (*env)->GetJavaVM(env, &g_VM) . This
reference will be later used within the C to Java callbacks.
2.
Convert the Java string array ( jargv ) to a C array ( char ** ). The C array will be
send to the native game loop. The key aspects of converting a Java string array
to a C array follow:
Get the length of the java array with (*env)->GetArrayLength(env, jarray) .
Get the value of the Nth row of the Java array as a Java string with jstring
jrow = (jstring)(*env)->GetObjectArrayElement(env, jargv, i).
Convert the Java string above ( jrow ) to a C string: const char *row =
(*env)->GetStringUTFChars(env, jrow, 0) .
Allocate space for the C array for that specific row: args[i] = malloc(
strlen(row) + 1) .
Copy the new C string to the C array: strcpy (args[i], row) .
Release the java string row: (*env)->ReleaseStringUTFChars(env, jrow,
row) .
Repeat the same process for each element in the Java array.
3.
Load the native interface class wolf.jni.Natives.java : jNativesCls = (*env)->
FindClass(env, "wolf/jni/Natives") . This class will be used by the C to Java
native callbacks.
4. Load the video update callback using its name and signature:
jSendImageMethod = (*env)->GetStaticMethodID(env, jNativesCls,
"OnImageUpdate", "([IIIII)V") .
5. Load the sound update callback: jStartSoundMethod = (*env)-
>GetStaticMethodID(env, jNativesCls, "OnStartSound", "(I)V") .
6. Invoke the native game loop sending the C array created previously: wolf_main
(clen, args) .
At this point, execution will block, and the native video buffer should fill up; plus native events
should start coming up. These events must be glued to the Android activity using the C to Java callbacks.
Listing 6-15. The Main Game Loop from wolf_jni.c
// Global Java VM
static JavaVM *g_VM;
// Java Native interface class
Search WWH ::




Custom Search