Return jint array from c to java via jni

I created an integer array in java and passed the array to the cpp program via jni My code:

import java.util.*; class SendArray { //Native method declaration native int[] loadFile(int[] name); //Load the library static { System.loadLibrary("nativelib"); } public static void main(String args[]) { int arr[] = {1,2,3,4,5,6,7,8,9,10}; //Create class instance SendArray mappedFile=new SendArray(); //Call native method to load SendArray.java int[] buf = mappedFile.loadFile(arr); //Print contents of SendArray.java for(int i=0;i<buf.length;i++) { System.out.print(buf[i]); } } } 

In the cpp program, I change the array and return the array back to the java program My code:

 #include <iostream> using namespace std; JNIEXPORT jintArray JNICALL Java_SendArray_loadFile (JNIEnv * env, jobject jobj, jintArray array) { cout<<"Orignal Array is:"<<endl; int i; jboolean j; int ar[100]; // for(i = 0; i < 10; i++){ int * p= env->GetIntArrayElements(array, &j); //jint *array=env->GetIntArrayElements(one, 0); //ar[i] = array[i]; //} for(i = 0 ; i < 10 ; i++){ cout << p[i]; } for(i = 10 ; i > 0 ; i--){ ar[10-i] = p[i]; } jintArray ret = env->NewIntArray(10); for(i = 0; i >10 ; i++){ ret[i]=ar[i]; } return ret; } 

Error: gettin:

 error: no match for 'operator=' in '*(ret +((long unsigned int)((long unsigned int)i))) = ar[i]' 

What should I do to return the array back to the java program ???? please, help!!!!!

+8
java jni
source share
1 answer

Instead, change your own code:

 JNIEXPORT jintArray JNICALL Java_SendArray_loadFile(JNIEnv *env, jobject obj, jintArray oldArray) { const jsize length = env->GetArrayLength(oldArray); jintArray newArray = env->NewIntArray(length); jint *oarr = env->GetIntArrayElements(oldArray, NULL); jint *narr = env->GetIntArrayElements(newArray, NULL); for (int o = 0, n = length - 1; o < length; o++, n--) { narr[n] = oarr[o]; } env->ReleaseIntArrayElements(newArray, narr, NULL); env->ReleaseIntArrayElements(oldArray, oarr, NULL); return newArray; } 

The main problem was that you tried to directly manipulate the ret object, and that is not possible. You must use JNI functions to control the jintArray object.

And you also need to make sure that you release your objects when you're done with them.

+13
source share

All Articles