创建两个native方法
public native void passArrayMethod(int[] arr);
public native int[] createArrayMethod(int len);
生成对应的c函数
JNIEXPORT void JNICALL Java_com_test_git_jnidemo_JniUtil_JniDemo_passArrayMethod
(JNIEnv *, jobject, jintArray)
JNIEXPORT jintArray JNICALL Java_com_test_git_jnidemo_JniUtil_JniDemo_createArrayMethod
(JNIEnv *, jobject, jint)
传递数组给JNI,修改第一个元素值,然后排序
int com(const void *a, const void *b){
return *(int *)a - *(int *)b;
}
JNIEXPORT void JNICALL Java_com_test_git_jnidemo_JniUtil_JniDemo_passArrayMethod
(JNIEnv *env, jobject jobj, jintArray jarr){
jint *arr = env->GetIntArrayElements(jarr, NULL);
*arr = 100;
int len = env->GetArrayLength(jarr);
qsort(arr, len, sizeof(jint), com);
env->ReleaseIntArrayElements(jarr, arr, JNI_COMMIT);
};
JNI生成数组,并返回
JNIEXPORT jintArray JNICALL Java_com_test_git_jnidemo_JniUtil_JniDemo_createArrayMethod
(JNIEnv *env, jobject jobj, jint len){
jintArray jarr = env->NewIntArray(len);
jint *arr = env->GetIntArrayElements(jarr, NULL);
int i = 0;
for(; i < len; i++){
arr[i] = i;
}
env->ReleaseIntArrayElements(jarr, arr, 0);
return jarr;
};
MainActivity中调用
int[] arr = {1, 3, 2, 6, 8, 0}
Log.i(TAG, "arr修改前: " + getArrayString(arr))
jd.passArrayMethod(arr)
Log.i(TAG, "arr修改后: " + getArrayString(arr))
Log.i(TAG, "------------------------------------------")
int[] arr_new = jd.createArrayMethod(10)
Log.i(TAG, "arr_new: "+ getArrayString(arr_new) )
输出结果:
09-26 17:02:29.454 994-994/com.test.git.jnidemo I/MainActivity-: arr修改前: ,1,3,2,6,8,0
09-26 17:02:29.454 994-994/com.test.git.jnidemo I/MainActivity-: arr修改后: ,0,2,3,6,8,100
09-26 17:02:29.454 994-994/com.test.git.jnidemo I/MainActivity-: ------------------------------------------
09-26 17:02:29.454 994-994/com.test.git.jnidemo I/MainActivity-: arr_new: ,0,1,2,3,4,5,6,7,8,9