JNI에서 Java로 배열을 반환하는 방법은 무엇입니까?
-
05-07-2019 - |
문제
Android NDK를 사용하려고합니다.
배열을 반환하는 방법이 있습니까 (제 경우에는 int[]
) JNI에서 Java에서 만들어 졌습니까? 그렇다면이 작업을 수행 할 JNI 기능의 빠른 예를 제공하십시오.
-감사
해결책
문서를 검토했지만 여전히 초기 질문의 일부가되어야하는 질문이 있다면. 이 경우, 예제의 JNI 함수는 여러 배열을 만듭니다. 외부 어레이는 JNI 함수를 사용한 '개체'배열로 구성됩니다. NewObjectArray()
. JNI의 관점에서 볼 때, 그것은 모두 2 차원 배열입니다. 다른 내부 배열이 포함 된 객체 배열입니다.
루프의 다음은 jni 함수를 사용하여 int [] 유형 인 내부 배열을 만듭니다. NewIntArray()
. 단일 차원의 int를 반환하고 싶다면 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 [] array를 반환하는 방법을 알고 싶다면 :
자바 코드
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
묻는 질문에 근거하여, 이것은 우리가 어떻게 우리가 jobjectarray를 통해 int []를 통과시킬 수 있다는 첫 번째 답변에서 이미 설명되어 있습니다. 그러나 다음은 데이터 목록이 포함 된 JobjectArray를 반환하는 방법이 있습니다. 예를 들어 상황에 도움이 될 수 있습니다. 누군가가 2D 형식으로 데이터를 반환하여 x 및 y 포인트가있는 선을 그릴 때 도움이 될 수 있습니다. 아래 예제는 JobjectArray가 다음 형식의 형태로 데이터를 반환 할 수있는 방법을 보여줍니다.
JNI에 대한 Java 입력 :
정렬[Arraylist
x 플로트 포인트] [Arraylist
y 플로트 포인트
JNI 출력 Java :
jobjectArray
[Arraylist
x 플로트 포인트] [Arraylist
y 플로트 포인트
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;
간단한 솔루션은 C의 파일에 배열 데이터를 작성한 다음 Java에서 파일에 액세스하는 것입니다.