JNI에서 Java로 배열을 반환하는 방법은 무엇입니까?
안드로이드 NDK를 사용하려고합니다.
int[]
JNI에서 생성 된 배열 (제 경우에는 )을 Java 로 반환하는 방법이 있습니까? 그렇다면,이를 수행하는 JNI 기능의 빠른 예를 제공하십시오.
-감사
문서를 검토했지만 여전히 초기 질문의 일부가되어야하는 질문이있는 경우 이 경우 예제의 JNI 함수는 여러 배열을 작성합니다. 외부 배열은 JNI 함수로 생성되는 'Object'배열로 구성됩니다 NewObjectArray()
. JNI의 관점에서 볼 때, 그것은 2 차원 배열입니다. 다수의 다른 내부 배열을 포함하는 객체 배열입니다.
다음 for 루프는 JNI 함수를 사용하여 int [] 유형의 내부 배열을 작성합니다 NewIntArray()
. int의 1 차원 배열을 반환하려면 NewIntArray()
함수가 반환 값을 만드는 데 사용하는 것입니다. 문자열의 단일 차원 배열을 만들려면 NewObjectArray()
함수를 사용 하지만 클래스에 다른 매개 변수를 사용하십시오.
int 배열을 반환하려고하므로 코드는 다음과 같습니다.
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;
}
누군가 String [] 배열을 반환하는 방법을 알고 싶다면 :
자바 코드
private native String[] data();
기본 수출
JNIEXPORT jobjectArray JNICALL Java_example_data() (JNIEnv *, jobject);
네이티브 코드
JNIEXPORT jobjectArray JNICALL
Java_example_data
(JNIEnv *env, jobject jobj){
jobjectArray ret;
int i;
char *message[5]= {"first",
"second",
"third",
"fourth",
"fifth"};
ret= (jobjectArray)env->NewObjectArray(5,
env->FindClass("java/lang/String"),
env->NewStringUTF(""));
for(i=0;i<5;i++) {
env->SetObjectArrayElement(
ret,i,env->NewStringUTF(message[i]));
}
return(ret);
}
링크에서 : http://www.coderanch.com/t/326467/java/java/Returning-String-array-program-Java
Based on the asked question, this is already explained in the first answer that how can we pass int[] via jobjectArray. But Here is an example how we can return a jobjectArray which contains lists of data. This can be helpful for situations for example: when someone needs to return data in 2D format to draw some line with x and y points. The below example shows how a jobjectArray can return data in the form of following format:
Java input to the JNI:
Array[Arraylist
of x float points][Arraylist
of y float points]
JNI output to java:
jobjectArray
[Arraylist
of x float points] [Arraylist
of y float points]
extern "C" JNIEXPORT jobjectArray JNICALL
_MainActivity_callOpenCVFn(
JNIEnv *env, jobject /* this */,
jobjectArray list) {
//Finding arrayList class and float class(2 lists , one x and another is y)
static jclass arrayListCls = static_cast<jclass>(env->NewGlobalRef(env->FindClass("java/util/ArrayList")));
jclass floatCls = env->FindClass("java/lang/Float");
//env initialization of list object and float
static jmethodID listConstructor = env->GetMethodID(arrayListCls, "<init>", "(I)V");
jmethodID alGetId = env->GetMethodID(arrayListCls, "get", "(I)Ljava/lang/Object;");
jmethodID alSizeId = env->GetMethodID(arrayListCls, "size", "()I");
static jmethodID addElementToList = env->GetMethodID(arrayListCls, "add", "(Ljava/lang/Object;)Z");
jmethodID floatConstructor = env->GetMethodID( floatCls, "<init>", "(F)V");
jmethodID floatId = env->GetMethodID(floatCls,"floatValue", "()F");
//null check(if null then return)
if (arrayListCls == nullptr || floatCls == nullptr) {
return 0;
}
// Get the value of each Float list object in the array
jsize length = env->GetArrayLength(list);
//If empty
if (length < 1) {
env->DeleteLocalRef(arrayListCls);
env->DeleteLocalRef(floatCls);
return 0;
}
// Creating an output jObjectArray
jobjectArray outJNIArray = env->NewObjectArray(length, arrayListCls, 0);
//taking list of X and Y points object at the time of return
jobject xPoint,yPoint,xReturnObject,yReturnObject;
//getting the xList,yList object from the array
jobject xObjFloatList = env->GetObjectArrayElement(list, 0);
jobject yObjFloatList = env->GetObjectArrayElement(list, 1);
// number of elements present in the array object
int xPointCounts = static_cast<int>(env->CallIntMethod(xObjFloatList, alSizeId));
static jfloat xReturn, yReturn;
jobject xReturnArrayList = env->NewObject(arrayListCls,listConstructor,0);
jobject yReturnArrayList = env->NewObject(arrayListCls,listConstructor,0);
for (int j = 0; j < xPointCounts; j++) {
//Getting the x points from the x object list in the array
xPoint = env->CallObjectMethod(xObjFloatList, alGetId, j);
//Getting the y points from the y object list in the array
yPoint = env->CallObjectMethod(yObjFloatList, alGetId, j);
//Returning jobjectArray(Here I am returning the same x and points I am receiving from java side, just to show how to make the returning `jobjectArray`)
//float x and y values
xReturn =static_cast<jfloat >(env->CallFloatMethod(xPoint, floatId,j));
yReturn =static_cast<jfloat >(env->CallFloatMethod(yPoint, floatId,j));
xReturnObject = env->NewObject(floatCls,floatConstructor,xReturn);
yReturnObject = env->NewObject(floatCls,floatConstructor,yReturn);
env->CallBooleanMethod(xReturnArrayList,addElementToList,xReturnObject);
env->CallBooleanMethod(yReturnArrayList,addElementToList,yReturnObject);
env->SetObjectArrayElement(outJNIArray,0,xReturnArrayList);
env->SetObjectArrayElement(outJNIArray,1,yReturnArrayList);
__android_log_print(ANDROID_LOG_ERROR, "List of X and Y are saved in the array","%d", 3);
}
return outJNIArray;
Simple solution is that write the array data in a file from C,and then access the file from Java
참고URL : https://stackoverflow.com/questions/1610045/how-to-return-an-array-from-jni-to-java
'Programming' 카테고리의 다른 글
git am과 git apply의 차이점은 무엇입니까? (0) | 2020.07.14 |
---|---|
핑 응답 "요청 시간이 초과되었습니다." (0) | 2020.07.14 |
html5 입력 유형 번호로 부동 소수점 및 소수 구분 기호를 처리하는 방법 (0) | 2020.07.14 |
Maven에서 외부 속성 파일을 읽는 방법 (0) | 2020.07.14 |
스칼라 열거 이해 (0) | 2020.07.14 |