Game Development Reference
In-Depth Information
Getting the Size of a Java Array
To get the size of a Java array, use the JNI function
(*env)->GetArrayLength(env, jobjectArray jarray)
,
where
env
is a pointer to the JNI environment, and
jarray
is a reference to the Java array. For example, to
get the size of the array
jargs
using environment
env
, use the following:
(*env)->GetArrayLength(env, jargs)
Invoking a Java Static Void Method
To invoke the static void
jni.Natives.OnMessage
method. you must perform the following steps:
1. Load the
jni.Natives
class with the following:
(*env)->FindClass(env, "jni/Natives")
2. Get the ID of the method to be invoked using a reference to the
jni.Natives
class, the name of the method (
OnMessage
), and the signature
(Ljava/lang/String;I)V
.
jmethodID mSendStr = (*env)->GetStaticMethodID(env
, jNativesCls
, "OnMessage"
, "(Ljava/lang/String;I)V");
3. Call the static void method, passing the class, method ID, and the method
arguments: a Java string and integer in this case.
(*env)->CallStaticVoidMethod(env, jNativesCls
, mSendStr
, (*env)->NewStringUTF(env, text)
, (jint) level );
Defining a Variable-Arguments Function in C
The final piece of the puzzle is a function to perform the actual invocation of the Java method described
in the previous section, as shown in Listing 2-5. This function is meant to be called anywhere within the
library after
jni.Natives.LibMain()
is invoked. It is called
jni_printf
and works pretty much as
printf
does, using the very useful variable-arguments technique.
Listing 2-5.
Sending a String to Java Using Variable Arguments
void jni_printf(char *format, ...)
{
va_list argptr;
static char string[1024];
va_start (argptr, format);
vsprintf (string, format, argptr);
va_end (argptr);