问题描述
我试图使用Android NDK。
I am attempting to use the android NDK.
有没有办法返回一个数组(在我的情况下, INT []
)创造了JNI到Java?如果有,请提供JNI函数的一个简单的例子,将做到这一点。
Is there a way to return an array (in my case an int[]
) created in JNI to Java? If so, please provide a quick example of the JNI function that would do this.
- 谢谢
推荐答案
如果您已经检查的文件,仍然有这应该是你最初的问题的一部分问题。在这种情况下,在该示例JNI函数创建许多阵列。外部阵列由一个'对象'创建数组用JNI函数 NewObjectArray()
的。从JNI的角度来看,这是所有的二维阵列是,包含许多其它内阵列的一个目的数组。
If you've examined the documentation and still have questions that should be part of your initial question. In this case, the JNI function in the example creates a number of arrays. The outer array is comprised of an 'Object' array creating with the JNI function NewObjectArray()
. From the perspective of JNI, that's all a two dimensional array is, an object array containing a number of other inner arrays.
下面的for循环创建这是类型为int []使用JNI函数的内部数组 NewIntArray()
。如果你只是想返回整数的一维数组,那么 NewIntArray()
的功能是你会用什么来创造的返回值。如果你想创建一个字符串的一维数组,那么你会使用 NewObjectArray()
的功能,但使用不同的参数类。
The following for loop creates the inner arrays which are of type int[] using the JNI function NewIntArray()
. If you just wanted to return a single dimensional array of ints, then the NewIntArray()
function is what you'd use to create the return value. If you wanted to create a single dimensional array of Strings then you'd use the NewObjectArray()
function but with a different parameter for the class.
由于要返回一个int数组,那么你的code将会是这个样子:
Since you want to return an int array, then your code is going to look something like this:
JNIEXPORT jintArray JNICALL Java_ArrayTest_initIntArray(JNIEnv *env, jclass cls, int size)
{
jintArray result;
result = (*env)->NewIntArray(env, size);
if (result == NULL) {
return NULL; /* out of memory error thrown */
}
int i;
// fill a temp structure to use to populate the java int array
jint fill[256];
for (i = 0; i < size; i++) {
fill[i] = 0; // put whatever logic you want to populate the values here.
}
// move from the temp structure to the java structure
(*env)->SetIntArrayRegion(env, result, 0, size, fill);
return result;
}
这篇关于如何从JNI返回数组到Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!