Game Development Reference
In-Depth Information
Converting a Java Array to a C Array
Converting a Java string array to a C char array is a very useful tool to send arguments to a native library.
As you can see from Listing 2-4, this can be a tricky situation. The following are the key steps:
Get the size of the Java array, and for each element of the array:
Get the Java String[i] element using GetObjectArrayElement(JNIEnv * env,
jobjectArray jarray, int pos) .
Convert the retrieved element into a C string ( char * ) using
GetStringUTFChars(JNIEnv * env, jstring jrow, 0) .
Allocate space for the C array using malloc(length of string + 1) . Note that an
extra space is allocated for the terminator character.
Copy the characters using strcpy (char ** target , char * source) .
Release Java String[i] using ReleaseStringUTFChars (JNIEnv * env, jstring
jrow, char * row) .
Listing 2-4. Converting a Java String Array into a C Char Array
// Extract char ** args from Java array
jsize clen = getArrayLen(env, jargv);
char * args[(int)clen];
int i;
jstring jrow;
// Loop thru Java array
for (i = 0; i < clen; i++)
{
// Get String[i]
jrow = (jstring)(*env)->GetObjectArrayElement(env, jargv, i);
// Convert String[i] to char *
const char *row = (*env)->GetStringUTFChars(env, jrow, 0);
// Allocate space
args[i] = malloc( strlen(row) + 1);
// Copy
strcpy (args[i], row);
// Free java string jrow
(*env)->ReleaseStringUTFChars(env, jrow, row);
}
Search WWH ::




Custom Search