Java Reference
In-Depth Information
Here it is necessary to have a pre-allocated buffer of the required size. Over-
running the buffer results in unpredictable results. The function performs array
bounds checking on the - jarray , throwing an ArrayIndexOutOfBounds-
Exception if one attempts to extract a region that is beyond the range of the
original Java array. The Web Course provides an example program that uses Get-
IntArrayRegion() to sum elements 5 to 14 of a long integer array. In general
the “region” methods are preferred, especially for short arrays, because they do
no memory allocation.
Recall that Java arrays contain length information in addition to the array
elements. In Java, the length is obtained directly from the length field of the
array (i.e. int len = array.length ). A useful function for getting the size
of a jxxxArray type on the C side is the GetArrayLength() function.
This function can be used to ensure that the region buffer for a GetXxxAr-
rayRegion() function call is sized large enough. GetArrayLength() takes
a jarray as an argument. The jarray type can be thought of as a “super-
type” of all the individual jxxxArray types, so any jxxxArray type can be
passed to GetArrayLength() , including a jobjectArray ,tobediscussed
below.
There are also SetXxxArrayRegion() functions for each primitive xxx
type. These “set” functions permit copying a C-side buffer directly into a
region of a jarray . The Web Course provides an example program that uses
SetIntArrayRegion() to set elements 5 to 14 of a long Java int array.
22.6.2 Creating new primitive arrays
If the native implementation needs to create a new Java primitive array, then it
does so using one of the NewXxxArray() functions. For example to create a
new jintArray ten elements long, we use
jintArray my - jarray = jenv->NewIntArray (10);
if (my - jarray == NULL)
return NULL;
As this function allocates memory, one should be sure to check for a NULL return
value and react accordingly. About the only reason to create a new j array on
the C side is for return to Java.
22.7 Java object arrays and multidimensional
primitive arrays
While it is easy for JNI to provide the jintArray , jfloatArray , etc. types
for convenience, there is no way to provide types for arbitrary Java objects on the
C side. An array of objects, such as MyCustomObject[] ,onthe Java side gets
passed to the C side as a jobjectArray . Unlike with the primitive arrays, there
Search WWH ::




Custom Search