Java Reference
In-Depth Information
JVM whenever inside any native method rather that attempting to save a copy of
the interface pointer.
22.4.2 Calling conventions
The JVM always uses the standard library calling convention for a given platform,
though that calling convention is likely to be different on different underlying
platforms. On Unix platforms, the C calling convention is used; on Windows,
the
--
stdcall
convention. Fortunately, this situation is completely transpar-
ent to the programmer. The only requirement is that the programmer write the
implementation to match the signatures in the generated header file and compile
the implementation on the target native platform. A native implementation can
be moved to another platform and recompiled without changes to the source code
on either the Java side or the native side. The
jni.h
file on each platform trans-
parently handles the differences in calling conventions between platforms. (Of
course, if the native implementation uses platform-specific features, then those
features have to be ported to the new native platform.)
Primitive type values -
int
,
float
,
char
, etc. - are copied (passed by value)
between the Java and native sides, automatically accounting for field size and
byte order through the defined
jint
,
jfloat
, etc. types. Java objects, including
arrays, are passed by object references, but the object references seen on the
C/C
side are the intermediate data types described in Section 22.4. Therefore,
the JNI library provides special JNI functions to access array elements and the
fields internal to a Java object. The next two sections deals with Java
String
objects and arrays in more detail.
++
22.5 Java
String
objects
Java
String
objects are quite different from C strings. For one thing, Java
Strings
are full-fledged objects with both state and behavior (i.e. data and
methods) while C strings are simply
char
arrays. When the JVM passes a Java
String
to a native C or C
implementation, a
jstring
is received in its
place. Just what is a
jstring
?Itiscertainly not a C string, and attempting to
treat it as one inside the native code likely results in a crash of the JVM. Actually,
a
jstring
is typedef'ed in
jni.h
to be a
jobject
and could be manipulated
like any other
jobject
(more about that appears below). However, because
strings are so important, JNI provides special functions for converting
jstring
types into C strings. A similar situation applies to Java arrays, which we discuss
after taking a look at the JNI string-related functions.
Recall that Java
Strings
are stored as Unicode characters, and that C strings
are arrays of C
char
types, which are 8-bit fields. Normally, C strings are com-
posed of just the 7-bit ASCII characters with the eighth bit of the
char
empty. To
convert Java strings into C strings, it is necessary to convert the Unicode string
++
Search WWH ::
Custom Search