分两种情况:
(1)基本元素数组
(2)对象数组
(1)基本元素数组
(i)拷贝基本元素数组:
JNIEXPORT jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr)
{
jint buf[10];
jint i, sum = 0;
(*env)->GetIntArrayRegion(env, arr, 0, 10, buf); //arr-->buf
for (i = 0; i < 10; i++) {
sum += buf[i];
}
return sum;
}
GetIntArrayRegion的第三个参数0表示arr的起始索引,第四个参数10表示要拷贝的元素个数.
(ii)获取基本元素数组的指针:
GetIntArrayElements/ReleaseIntArrayElements
JNIEXPORT jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr)
{
jint *carr;
jint i, sum = 0;
carr = (*env)->GetIntArrayElements(env, arr, NULL);
if (carr == NULL) {
return 0; /* exception occurred */
}
for (i=0; i<10; i++) {
sum += carr[i];
}
(*env)->ReleaseIntArrayElements(env, arr, carr, 0);
return sum;
}
(2)对象数组
获取/设置对象数组:
GetObjectArrayElement/SetObjectArrayElement
JNIEXPORT jobjectArray JNICALL Java_ObjectArrayTest_initInt2DArray(JNIEnv *env,jclass cls,int size)
{
jobjectArray result;
int i;
jclass intArrCls = (*env)->FindClass(env, "[I"); //int[]!!!
if (intArrCls == NULL) {
return NULL; /* exception thrown */
}
result = (*env)->NewObjectArray(env, size, intArrCls,NULL);
if (result == NULL) {
return NULL; /* out of memory error thrown */
}
for (i = 0; i < size; i++) {
jint tmp[256]; /* make sure it is large enough! */
int j;
jintArray iarr = (*env)->NewIntArray(env, size);
if (iarr == NULL) {
return NULL; /* out of memory error thrown */
}
for (j = 0; j < size; j++) {
tmp[j] = i + j;
}
(*env)->SetIntArrayRegion(env, iarr, 0, size, tmp);
(*env)->SetObjectArrayElement(env, result, i, iarr);
(*env)->DeleteLocalRef(env, iarr);
}
return result;
}
如上代码创建一个二维数组,如果size设置为3,二维数组如下:
0 1 2
1 2 3
2 3 4
参考资料:
[1]The Java™ Native Interface Programmer’s Guide and Specification.pdf
来源:CSDN
作者:羽落长安
链接:https://blog.csdn.net/u012906122/article/details/103834739