Java Reference
In-Depth Information
We note that
GetStringUTFRegion()
was not in the original JNI speci-
fication. It was added for Java 2 SDK version 1.2 (commonly called JDK 1.2)
meaning it has been around for several years now. Unfortunately, it can be easy
to miss the documentation about
GetStringUTFRegion()
and a few other
new JNI functions because of the way the JNI documentation is organized. Most
of the JNI functions are described in the online docs [1] in the section titled
“JNI 1.1 Specification”. The enhancements added since Java 1.1 appear in the
section labeled JNI Enhancements, below which are links to “JNI Enhancements
in version 1.2”, and “JNI Enhancements in version 1.4”. In order to see all the
JNI functions, you need to follow the links to all three documents. (Fortunately,
this situation has improved with the J2SE 5.0 document set where all the JNI
functions are combined into one document.)
One might also come across some (scant) documentation (see the
JNI Pro-
grammer's Guide
[3]) referring to a
SetStringUTFRegion()
function that
permits directly setting the characters in a region of a
jstring
. This function
would be analogous to the
“
Set
„
functions for array elements, to be discussed
later. However, to the best of our knowledge, such a function does not really exist
in JNI.
The Web Course contains a simple string handling example in files
called
StringExample.java
and
NativeString.cpp
. The string handling
example takes an input string and uses C code to reverse the order of the char-
acters. The reversed string is returned as the return value of the native method.
Of course the same thing could be done purely in Java. The example is simply
meant to illustrate the use of the JNI string handling functions.
When the native method declaration declares the method return to be
String
,
as our
nativeProcessString
example does, the value returned to the calling
Java code must be a Java
String
.Tocreate one on the native side, the native code
uses the
NewStringUTF()
function which takes a C array of UTF-8 characters
as an input argument and creates and returns a
jstring
. When the
jstring
is returned to the calling Java code, it is converted to a Java
String
by the JNI
subsystem. The code to create the new
jstring
appears as follows, assuming
that the C string
reverse
has already been populated with the reversed-order
version of the input string:
jstring jreverse
=
jenv-
>
NewStringUTF (reverse);
return jreverse;
Like
GetStringUTFChars()
,
NewStringUTF()
must allocate memory, so
it is written to return
NULL
and throw an
OutOfMemoryError
if memory for
the new
jstring
cannot be allocated. In general, the returned value should
be checked and appropriate action should be taken if it is
NULL
. Here, however,
since we immediately return the value obtained from
NewStringUTF()
anyway,
there is no explicit need to check for a
NULL
return.
Search WWH ::
Custom Search