通过jni将jint数组从C返回到Java [英] Returning jint array from c to java through jni
问题描述
我在Java中创建了一个整数数组,并将该数组通过jni传递给cpp程序 我的代码是:
I have created an integer array in java and passed the array to a cpp programme through jni My Code is:
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]);
}
}
}
在cpp程序中,我正在反转数组并将数组返回给java programee 我的代码是::
In cpp programme I am reversing the array and returning the array back to java programee My Code is::
#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: no match for 'operator=' in '*(ret +((long unsigned int)((long unsigned int)i))) = ar[i]'
我应该怎么做才能将数组返回到Java程序????请帮忙!!!!!
What should I do to return the array back to java programme???? 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;
}
您的主要问题是您试图直接操作ret
对象,而这是不可能的.您必须使用JNI函数来操作jintArray
对象.
Your main problem was that you tried to manipulate the ret
object directly and that is not possible. You have to use JNI functions to manipulate a jintArray
object.
并且还必须确保在处理完对象后释放它们.
And you also have to make sure you release your objects when done with them.
这篇关于通过jni将jint数组从C返回到Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!