Java Reference
In-Depth Information
There are a few other JNI string handling functions, particularly GetStr-
ingChars() and ReleaseStringChars() . These are useful for getting
string characters in Unicode format instead of UTF-8 characters. Doing so is
not relevant to this topic and is not discussed further.
22.6 Java primitive arrays
Arrays in Java can be arrays of Java primitives (e.g. float[] )orarraysofJava
objects. Arrays of Java primitive types are treated similarly to Java strings in
JNI. Both are objects on the Java side, both are passed to native methods as
object references, and both have special types defined in jni.h on the C side
for convenience. Object arrays are a bit more complicated than primitive arrays,
and we discuss them in the next section.
AJava primitive array of Java float sispassed to a JNI method as a
jfloatArray . There are also jintArray , jbyteArray , jdoubleArray ,
etc. types for the other Java primitives. Just like a jstring is not a C string,
neither is a jfloatArray an array of C/C
++ float s. And, just like with
strings, JNI provides special functions for converting the various jxxxArray
types into corresponding C/C
arrays. One of the special functions for
converting jfloatArray types is getFloatArrayElements() ,which
returns a pointer to an array of C float s. Given a jfloatArray called
the - jfloatarray ,weobtainaCarrayasfollows:
++
float* c - array = jenv->GetFloatArrayElements (
the - jfloatarray, NULL);
if (c - array == NULL) {
return 0.;
}
// Use c - array in some way, and then
ReleaseFloatArrayElements (the - jfloatarray, c - array, 0);
...
Here we have converted the - jfloatarray into an array of C float s. The JNI
function GetFloatArrayElements() allocates the space for the C array, per-
forms the conversion, and returns a pointer to the new C array. Since the function
must allocate enough memory for the C array we must be sure to check the return
value for NULL and respond accordingly, just like we did with GetStringUT-
FChars() above. After c - array has been used, we must be certain to clean
up by calling ReleaseFloatArrayElements() . Similar code applies for all
the other primitive array types.
During garbage collection on the Java side, Java arrays may be moved in mem-
ory without warning. The JVM ensures that a garbage collection event does not
impact behavior on the Java side. For native code, the JVM also guarantees that the
C side array does not move in memory unexpectedly. It does so by either making a
copy of the Java array elements for use on the C side, where the copy is not subject
Search WWH ::




Custom Search