返回数组¶
返回数组,例如int数组,float数组等等。
返回新的int数组¶
新创建jintArray
并返回。
生成jintArray
,需要调用NewIntArray
方法。生成数组后,需要SetIntArrayRegion
方法将数据填充进去。
extern "C"
JNIEXPORT jintArray JNICALL
Java_com_rustfisher_fishpole_worker_BaseParam_nGenIntArray(JNIEnv *env, jobject thiz) {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int len = sizeof(arr) / sizeof(arr[0]);
jintArray resArr = env->NewIntArray(len);
env->SetIntArrayRegion(resArr, 0, len, arr);
return resArr;
}
操作数组中的元素¶
输入一个数组,修改里面的数据。
输入的jintArray
可以用GetArrayLength
方法获取长度。
通过GetIntArrayElements
拿到指针。
修改后再把数据复制到jintArray
中。
extern "C"
JNIEXPORT void JNICALL
Java_com_rustfisher_fishpole_worker_BaseParam_nModifyIntArray(JNIEnv *env, jobject thiz,
jintArray input) {
int len = env->GetArrayLength(input);
int* ptr = env->GetIntArrayElements(input, JNI_FALSE);
for(int i = 0; i < len; i++) {
ptr[i] = i + len;
}
env->ReleaseIntArrayElements(input, ptr, JNI_COMMIT);
delete ptr;
}
ReleaseIntArrayElements
第3个参数说明:
- 0 Updates to the array from within the C code are reflected in the Java language copy.
- JNI_COMMIT forces the native array to be copied back to the original array in the Java virtual machine.
- JNI_ABORT frees the memory allocated for the native array without copying back the new contents.
上面我们使用的是JNI_COMMIT,把native数组的值复制到Java的数组中。
作者: rustfisher.com | rf.cs@foxmail.com
示例: AndroidTutorial Gitee, Tutorial Github
本文链接: https://www.an.rustfisher.com/android/ndk/return/return-array/
一家之言,仅当抛砖引玉。如有错漏,还请指出。如果喜欢本站的内容,还请支持作者。也可点击1次下方的链接(链接内容与本站无关),谢谢支持服务器。
如有疑问,请与我联系:Android issues - gitee