Java Reference
In-Depth Information
into UTF-8 encoding (see Chapter 9), something that C and C
can use. UTF-8
maps, and fits, into C's 8-bit char representation. Generally, the results are as
expected as long as the original string contains only characters in the ASCII range
of UTF-8, which is a good idea for anyone using a C or C
++
++
native implementa-
tion since those languages don't provide native support for non-ASCII characters
anyway. Special care must be taken in the native implementation to deal with
non-ASCII strings. The examples in this topic always assume ASCII strings.
The main JNI function for working with jstring types is GetString-
UTFChars() ,which converts the internal Unicode Java string into a UTF-8
representation. Suppose we have a native method declared as follows:
package javatech.jni22;
public class StringExample {
...
public native String nativeProcessString (String s);
...
}
This native method receives a Java String , processes it somehow, and returns a
Java String . The native method signature is obtained from the generated header
file after running javah . Thus the beginning of the C/C
++
implementation looks
like this:
JNIEXPORT jstring JNICALL
Java - javatech - jni22 - StringExample - nativeProcessString
(JNIEnv *jenv, jobject jo, jstring js) {
// code to do the processing
...
}
Note here that the single String parameter on the Java side appears as a
jstring in the third argument on the C side, after the JNIEnv pointer and
the jobject . Also note that the C function is declared to return a jstring .
The first thing we must do is convert the received jstring to a C string. To
do so, the C
++
calling sequence is
const char* cs = jenv->GetStringUTFChars (js, NULL);
if (cs == NULL) {
// Handle the error and return immediately
return NULL;
}
// Use cs in some way ...
...
jenv- > ReleaseStringUTFChars (js, cs);
...
Search WWH ::




Custom Search