Calling C from Java   -   passing a String

JNI has two sets of string functions, one that converts Java strings to UTF (UCS Transformation Format) jstrings, and one that converts them to arrays of Unicode jchars. If all your Java strings are restricted to ASCII characters, you will want to use the first set of functions.

In the example, javah has converted the String parameter and the String return value to type jstring (lines 5 and 18-19). Three JNI functions are required here:

All calls to JNI functions use the env pointer that is supplied as the first argument of every native method. env is a pointer to a table of function pointers.

GetStringUTFChars() expects a jstring and a jboolean (the only example found to date hard-wires this second argument to zero), and returns a const char* that is usable by C code. Since Java strings are meant to be immutable, it is very important that you treat the const seriously and do not try to write into the returned character array.

NewStringUTF() returns a new Java string object from a UTF string, or NULL if the string cannot be constructed. ReleaseStringUTFChars() expects both the jstring received from the JVM, and, the const char* generated by the call to GetStringUTFChars().

[source: Horstmann98, pp588-593]