JNI Part 5: JNI Arrays

  1. Arrays have dimension. An array’s dimension determines the number of indexes needed to access an element.
  2. The standard convention for declaring arrays is:
    • String[] s; // one-dimensional array
    • String s[]; // one-dimensional array
    • String[][] s; // two-dimensional array
  3. Declaring the size of the array with the following notation is illegal:
    • String[5] s; // illegal declaration
  4. An array implicitly extends java.lang.Object. Therefore, an array is an instance of Object class. Hence, arrays in Java are objects.
  5. Declaring an array does not create an array object or allocate space in memory; it creates a variable with a reference to an array.
  6. Since arrays are Objects they can be initialized using the new operator.
  7. When created, arrays are automatically initialized with the default value of their type.
    • String[] s = new String[100];   // default values: null
    • boolean[] b = new boolean[4]; // default values: false
    • int[][] i = new int[10][10];        // default values: 0
  8. The JNI treats primitive arrays and object arrays differently.
  9. Primitive arrays contain elements that are of primitive types such as int and boolean.
  10. Object arrays contain elements that are of reference types such as class instances and other arrays.
    • int[] iarr;
    • float[] farr;
    • Object[] oarr;
    • int[][] arr2;
  11. Accessing primitive arrays in a native method requires the use of JNI functions similar to those used for accessing strings.
  12. The JNI Get<Type>ArrayRegion function copies all the elements in the JNI array into a C buffer of an appropriate type. The second argument is the starting index of the elements, and the third argument is the number of elements to be copied. Once the elements are in the C buffer, we can access them in native code.
    • Example: env->GetCharArrayRegion(arr, 0, arrLength, chArrRWB);
  13. The JNI also supports a corresponding Set<Type>ArrayRegion function that allows native code to modify the array elements. Arrays of all the primitive types (such as boolean, short, and float) are also supported.
  14. The JNI supports a family of Get/Release<Type>ArrayElements functions (for example, Get/ReleaseIntArrayElements) that allow the native code to obtain a direct pointer to the elements of primitive arrays.
  15. The GetArrayLength function returns the number of elements in primitive or object arrays.

Example: Accessing intarray

1
2
3
4
5
6
7
8
9
JNIExport jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj,
	jintArray arr){
		jsize len = *env->GetArrayLength(env,arr);
		jint *body = *env->GetIntArrayElements(env,arr,0);
		for (jint i = 0; i < len; ++i){
			sum += body[i];
		}
	*env->ReleastIntArrayElements(env, arr, body, 0);
}
JNI Function Description
Get<Type>ArrayRegion
Set<Type>ArrayRegion
Copies the contents of primitive arrays to or from a pre-allocated C buffer.
Get<Type>ArrayElements
Release<Type>ArrayElements
Obtains a pointer to the contents of a primitive array. May return a copy of the array.
GetArrayLength Returns the number of elements in the array.
New<Type>Array Creates an array with the given length.
GetPrimitiveArrayCritical
ReleasePrimitiveArrayCritical
Obtains or releases a pointer to the contents of a primitive array. These functions allow virtual machines to disable garbage collection while the native code accesses the contents of primitive arrays.

JNI Array Example program

Let’s write a JNI application that passes an unsorted integer array to a native method, which method sorts and sends it back to the application.

The Java code will be(SortArray.java):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class SortArray {
	private native int[] sort(int[] arr);  //native method 
 
	static   //static initializer code
	{
		System.loadLibrary("SortArray");
	} 
 
	public static void main(String[] args)
	{
		int iArr[] = {4,5,2,7,1,9}; // Input array
		int oArr[]; //Output array
 
		SortArray arr = new SortArray();
 
		System.out.println("Unsorted array: ");
		for(int i = 0; i < iArr.length; i++){
			System.out.println(iArr[i] + " ");
		}
 
		oArr = arr.sort(iArr);
 
		System.out.println("Sorted array: ");
		for(int i = 0; i < oArr.length; i++){
			System.out.println(oArr[i] + " ");
		}
	}
}

Compile SortArray.java (javac SortArray.java) and generate hedder file(javah -jni SortArray).

The generated with javah header file SortArray.h will be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class SortArray */
 
#ifndef _Included_SortArray
#define _Included_SortArray
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     SortArray
 * Method:    sort
 * Signature: ([I)[I
 */
JNIEXPORT jintArray JNICALL Java_SortArray_sort
  (JNIEnv *, jobject, jintArray);
 
#ifdef __cplusplus
}
#endif
#endif

The C++ implementation file SortArray.cpp will be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "SortArray.h"
#include "jni.h"
 
/*
 * Class:     SortArray
 * Method:    sort
 * Signature: ([I)[I
 */
JNIEXPORT jintArray JNICALL Java_SortArray_sort
    (JNIEnv *env, jobject obj, jintArray arr){
 
    jsize arrLength = env->GetArrayLength(arr);
    jintArray arrSorted = env->NewIntArray(arrLength); 
 
    jint *arrOut = NULL;
    arrOut = env->GetIntArrayElements(arr, 0);
 
    for(jsize x = 0; x < arrLength; x++){
        for(jsize y = 0; y < arrLength - 1; y++){
                        if(arrOut[y] > arrOut[y+1]){
				jsize temp = arrOut[y+1];
				arrOut[y+1] = arrOut[y];
				arrOut[y] = temp;
			}
		}
	}
 
    env->SetIntArrayRegion(arrSorted, 0, arrLength, arrOut);
    env->ReleaseIntArrayElements(arr, arrOut, 0);
 
    return arrSorted;
}

Run the program (java SortArray) and verify the output.

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

One thought on “JNI Part 5: JNI Arrays

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in