Java – How to return an “int array” from a native method to java in the NDK

How to return an “int array” from a native method to java in the NDK… here is a solution to the problem.

How to return an “int array” from a native method to java in the NDK

Take a look at my native functions in nativeLib

 public native int [] getArrayNative();

That’s how I use it

 private static int[] DEMO_NODES;

DEMO_NODES =  nativeLib.getArrayNative();

In C code there is

JNIEXPORT jintArray JNICALL Java_com_testing_NativeLib_getArrayNative
  (JNIEnv *env, jobject obj) {

int array[] = { 0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 1, 2, 1, 2, 3, 2, 3, 1, 2 };
    jintArray temp = (*env)->NewIntArray(env,20);
    temp[0] = array[0];    gives error
    return temp;    
}

Here I want to go back to the whole arry[] but I don’t understand how to do it.
Here I took the new temporary array internally, trying to copy the value of arry[], but it shows an error. So how to do it

Solution

Use SetIntArrayRegion to populate the array, jintArray is just some magic
Internal structure, you cannot access anything using the index.

Prototype void SetArrayRegion(JNIEnv *env, array,
jsize start, jsize len, *buf);

Related Problems and Solutions