新建数组
通过使用这New<Type>Array函数来构造一个新数组实例。数组的长度必须提供作为一个参数,当调用这些函数时。
存溢出,虚拟机异常时返回为空,提示Jni代码不应该继续。
获得数组的元素
代码获得一个数组的拷贝作为c数组,或者它询问JNI来得到一个数组元素的直接指针。
一个拷贝的操作
这个Get<Type>ArrayRegion函数拷贝原始的Java数组到给定的C数组。
jint nativeArray[10];
(*env)->GetIntArrayRegion(env, javaArray, 0, 10, nativeArray);
之后本地代码,可以可以使用和修改数组想c的普通数组一样。当本地想要提交改变到java数组时,可以使用set<Type>ArrayRegion来拷贝C数组到Java数组。
当数组长度大时,拷贝就会出错。
直接指针的应用
这个Get<Type>ArrayElements函数,得到数组元素的直接指针。第三个参数isCopy,指定the caller to determine whether the returned C array points to a copy or the pinned array in the heap.
jint* nativeDirectArray;
jboolean isCopy;
nativeDirectArray = (*env)->GetIntArrayElements(env, javaArray, &isCopy);
当完成时需要释放这些指针,故Release<Type>ArrayElements.
(*env)->ReleaseIntArrayElements(env, javaArray, nativeDirectArray, 0);
其中第四个参数,
0 Copy back the content and free the native array.
JNI_COMMIT Copy back the content but do not free the native array. This can be used for periodically updating a Java array.
JNI_ABORT Free the native array without copying its content.