[英]Returning jint array from c to java through jni
I have created an integer array in java and passed the array to a cpp programme through jni My Code is: 我在java中创建了一个整数数组,并通过jni将数组传递给cpp程序我的代码是:
import java.util.*;
class SendArray {
//Native method declaration
native int[] loadFile(int[] name);
//Load the library
static {
System.loadLibrary("nativelib");
}
public static void main(String args[]) {
int arr[] = {1,2,3,4,5,6,7,8,9,10};
//Create class instance
SendArray mappedFile=new SendArray();
//Call native method to load SendArray.java
int[] buf = mappedFile.loadFile(arr);
//Print contents of SendArray.java
for(int i=0;i<buf.length;i++) {
System.out.print(buf[i]);
}
}
}
In cpp programme I am reversing the array and returning the array back to java programee My Code is:: 在cpp程序中,我正在反转数组并将数组返回到java programee我的代码是::
#include <iostream>
using namespace std;
JNIEXPORT jintArray JNICALL Java_SendArray_loadFile
(JNIEnv * env, jobject jobj, jintArray array) {
cout<<"Orignal Array is:"<<endl;
int i;
jboolean j;
int ar[100];
// for(i = 0; i < 10; i++){
int * p= env->GetIntArrayElements(array, &j);
//jint *array=env->GetIntArrayElements(one, 0);
//ar[i] = array[i];
//}
for(i = 0 ; i < 10 ; i++){
cout << p[i];
}
for(i = 10 ; i > 0 ; i--){
ar[10-i] = p[i];
}
jintArray ret = env->NewIntArray(10);
for(i = 0; i >10 ; i++){
ret[i]=ar[i];
}
return ret;
}
error I am gettin is: 我得到的错误是:
error: no match for 'operator=' in '*(ret +((long unsigned int)((long unsigned int)i))) = ar[i]'
What should I do to return the array back to java programme???? 我该怎么做才能将数组返回给java程序???? please help!!!!!
请帮忙!!!!!
Change your native code to this instead: 将您的本机代码更改为:
JNIEXPORT jintArray JNICALL Java_SendArray_loadFile(JNIEnv *env, jobject obj, jintArray oldArray) {
const jsize length = env->GetArrayLength(oldArray);
jintArray newArray = env->NewIntArray(length);
jint *oarr = env->GetIntArrayElements(oldArray, NULL);
jint *narr = env->GetIntArrayElements(newArray, NULL);
for (int o = 0, n = length - 1; o < length; o++, n--) {
narr[n] = oarr[o];
}
env->ReleaseIntArrayElements(newArray, narr, NULL);
env->ReleaseIntArrayElements(oldArray, oarr, NULL);
return newArray;
}
Your main problem was that you tried to manipulate the ret
object directly and that is not possible. 你的主要问题是你试图直接操纵
ret
对象,这是不可能的。 You have to use JNI functions to manipulate a jintArray
object. 您必须使用JNI函数来操作
jintArray
对象。
And you also have to make sure you release your objects when done with them. 此外,您还必须确保在完成对象后释放它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.