|
|
|
|||
|
Java StringsWhen a Java application passes a string to a native method, it passes the string as ajstring type. This jstring type is
different from the regular C string type (char *). If your code tries to
print a jstring directly, it will likely result in a VM crash. For example, the following code segment incorrectly tries to print a jstring and may result in a VM crash:
Your native method code must use JNI functions to convert Java strings to native strings. The JNI supports the conversion to and from native Unicode and UTF-8 strings. In particular, UTF-8 strings use the highest bit-to-signal multibyte characters; they are therefore upwards-compatible with 7-bit ASCII. In Java, UTF-8 strings are always 0-terminated. Accessing Java StringsYour native method needs to callGetStringUTFChars to correctly print the string passed to it from a Java application. GetStringUTFChars converts the built-in Unicode representation of a
Java string into a UTF-8 string. Once you are certain that the
string only contains 7-bit ASCII characters, you can directly pass
the string to regular C language functions, such as printf,
as is shown in Prompt.c:
The native method can also construct a new string using the JNI
function
Using the JNIEnv Interface Pointer Native methods must access and manipulate Java objects, such as
strings, through the ![]() This figure has been reduced to fit on the page. Click the image to view it at its natural size. Other JNI Functions for Accessing Java StringsThe JNI also provides functions to obtain the Unicode representation of Java strings. This is useful, for example, on those operating systems that support Unicode as the native format. There are also utility functions to obtain both the UTF-8 and Unicode length of Java strings.
| |||
|