Game Development Reference
In-Depth Information
// Java
package quake.jni;
public class Natives {
...
public static native int QuakeMain(String[] argv);
...
}
// in jni_quake.c
JNIEXPORT jint JNICALL Java_quake_jni_Natives_QuakeMain
(JNIEnv * env, jclass cls, jobjectArray jargv)
Note that the Java string arguments map into a
jobjectArray
in C, and they must be
converted to the standard
char *
format. Fortunately, JNI provides the utility functions
GetArrayLength
,
GetObjectArrayElement
,
GetStringUTFChars
, and
ReleaseStringUTFChars
to
do this easily.
1.
First, get the size of the Java array using
GetArrayLength
.
jsize clen = (*env)->GetArrayLength(env, jargv);
2.
Next, allocate a C array of the same size.
char * args[(int)clen];
3.
Then, loop through the size value, extracting a Java string from the
array by calling
GetObjectArrayElement
, then converting that Java
string into a C string using
GetStringUTFChars
, as shown:
int i;
jstring jrow;
for (i = 0; i < clen; i++)
{
jrow = (jstring)(*env)->GetObjectArrayElement(env, jargv, i);
const char *row = (*env)->GetStringUTFChars(env, jrow, 0);
4.
Then, simply allocate space for the corresponding C string using the
malloc
system call.
args[i] = malloc( strlen(row) + 1);
strcpy (args[i], row);
5.
Make sure to release the Java string using
ReleaseStringUTFChars
when done. Failing to do so will create a memory leak.
// free java string jrow
(*env)->ReleaseStringUTFChars(env, jrow, row);
}