Game Development Reference
In-Depth Information
/**
* Event callback
*/
void jni_send_event(int wiimoteNum, char *format, ...)
{
va_list argptr;
static char string[1024];
va_start (argptr, format);
vsprintf (string, format,argptr);
va_end (argptr);
jni_send_str(wiimoteNum, "OnEvent", string);
}
You can see from the previous listing the way WiiC interacts with Java by simply sending
events encoded as strings by these functions:
jni_send_message : This function sends a string to the OnMessage method
of the Wiimote Java class. This class notifies the listener about the
message, which can then display it on screen. For example, to tell Java
that an N number of Wiimote(s) are connected, you could use
jni_send_message("Connected to %i wiimotes (of %i found).", connected, nmotes);
jni_send_event : This function sends event information to the Wiimote
class encoded as key/value sets delimited by |. For example, to notify
that the A button has been pressed, you use
jni_send_event(id, "EVT_TYPE=BTNPRESS|BTN=%s", "A");
Note that encoding events as strings avoids having to marshal objects between C and Java,
which is very difficult and makes the code unnecessarily complex and hard to maintain. As
a bonus, code can be reused greatly as both jni_send_message and jni_send_event simply
invoke jni_send_str with a different set of arguments. Other things that must be taken into
account in the callbacks in Listing 8-12 include
Thread safety : Because both callbacks are invoked outside of the main
thread, they must attach to the current thread by calling
(*g_VM)->AttachCurrentThread (g_VM, &env, NULL)
This is a basic rule of thumb of JNI development. If you don't do this, a
segmentation fault will occur and the app will crash.
Variable arguments : This is one of the most useful features of the C
language. The ability to pack dynamic arguments sent to a function into
a single variable for consumption. It is really a life saver. For example, a
function like void jni_send_message(char *format, ...) can pack its
sequence of arguments as shown in the following fragment:
va_list argptr;
static char string[1024];
 
Search WWH ::




Custom Search