如何将数组从 JNI 返回到 Java? [英] How to return an array from JNI to Java?

查看:25
本文介绍了如何将数组从 JNI 返回到 Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用安卓 NDK.

I am attempting to use the android NDK.

有没有办法将在 JNI 中创建的数组(在我的例子中是 int[])返回到 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 循环使用 JNI 函数 NewIntArray() 创建 int[] 类型的内部数组.如果您只想返回整数的一维数组,则可以使用 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 数组,那么你的代码看起来像这样:

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[size];
 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆