I'm new to JNI and C++, here I'm going to pass an array from Java in Android to JNI, and in the JNI just need sort the array in Bubble way. However, it's seems this never get worked, I mean the array never get sorted. I don't know whether the array had never been passed or there're some problems with the functions in JNI.
And following is the demo-code.
File .h :
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_jni_jniDemo_JniInterface */
#ifndef _Included_com_jni_jniDemo_JniInterface
#define _Included_com_jni_jniDemo_JniInterface
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_jni_jniDemo_JniInterface
* Method: getString
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jintArray JNICALL Java_com_jni_jniDemo_JniInterface_arraySort
(JNIEnv *, jobject, jintArray);
#ifdef __cplusplus
}
#endif
#endif
File .cpp :
int sort(int &a, int &b){
a = a + b;
b = a - b;
a = a - b;
}
JNIEXPORT jintArray JNICALL
Java_com_jni_jniDemo_JniInterface_arraySort(JNIEnv *env, jobject obj, jintArray jArr) {
jint *arr = env -> GetIntArrayElements(jArr, 0);
int len = env -> GetArrayLength(jArr);
for(int i = 0; i < len; i++){
for(int j = 0; j < len - i -1; j++){
if(arr[j] > arr[j + 1]){
sort(arr[j], arr[j + 1]);
}
}
}
env -> ReleaseIntArrayElements(jArr, arr, JNI_COMMIT);
return jArr;
}
File .java :
private int[] array = {7, 34, 2, 44, 6, 0, 127, 9};
private int[] newArray;
for(int i = 0; i < array.length; i++){
System.out.println("Before sort:" + String.valueOf(array[i]));
}
jniInterface = new JniInterface();
newArray = jniInterface.arraySort(array);
for(int j = 0; j < newArray.length; j++){
System.out.println("After sort:" + String.valueOf(newArray[j]));
}
Any ideas?