Next: , Previous: Memory allocation, Up: About CNI

9.10 Arrays

While in many ways Java is similar to C and C++, it is quite different in its treatment of arrays. C arrays are based on the idea of pointer arithmetic, which would be incompatible with Java's security requirements. Java arrays are true objects (array types inherit from java.lang.Object). An array-valued variable is one that contains a reference (pointer) to an array object.

Referencing a Java array in C++ code is done using the JArray template, which as defined as follows:

     class __JArray : public java::lang::Object
       int length;
     template<class T>
     class JArray : public __JArray
       T data[0];
       T& operator[](jint i) { return data[i]; }

There are a number of typedefs which correspond to typedefs from the JNI. Each is the type of an array holding objects of the relevant type:

     typedef __JArray *jarray;
     typedef JArray<jobject> *jobjectArray;
     typedef JArray<jboolean> *jbooleanArray;
     typedef JArray<jbyte> *jbyteArray;
     typedef JArray<jchar> *jcharArray;
     typedef JArray<jshort> *jshortArray;
     typedef JArray<jint> *jintArray;
     typedef JArray<jlong> *jlongArray;
     typedef JArray<jfloat> *jfloatArray;
     typedef JArray<jdouble> *jdoubleArray;
— Method on template<class T>: T* elements (JArray<T> array)

This template function can be used to get a pointer to the elements of the array. For instance, you can fetch a pointer to the integers that make up an int[] like so:

          extern jintArray foo;
          jint *intp = elements (foo);

The name of this function may change in the future.

— Function: jobjectArray JvNewObjectArray (jsize length, jclass klass, jobject init)

This creates a new array whose elements have reference type. klass is the type of elements of the array and init is the initial value put into every slot in the array.

     using namespace java::lang;
     JArray<String *> *array
       = (JArray<String *> *) JvNewObjectArray(length, &String::class$, NULL);

9.10.1 Creating arrays

For each primitive type there is a function which can be used to create a new array of that type. The name of the function is of the form:


For example:


can be used to create an array of Java primitive boolean types.

The following function definition is the template for all such functions:

— Function: jbooleanArray JvNewBooleanArray (jint length)

Creates an array length indices long.

— Function: jsize JvGetArrayLength (jarray array)

Returns the length of the array.