Pergunta

Eu estou tentando usar o Android NDK.

Existe uma maneira de retornar um array (no meu caso um int[]), criado em JNI para Java? Se assim for, por favor, fornecer um exemplo rápido da função JNI que faria isso.

-Obrigado

Foi útil?

Solução

Se você já examinou a documentação e ainda ter perguntas que devem fazer parte da sua pergunta inicial. Neste caso, a função JNI no exemplo cria um certo número de matrizes. A matriz exterior é composta por uma matriz 'Objecto' criando com o NewObjectArray() função JNI. Do ponto de vista de JNI, que é tudo uma matriz bidimensional é, uma matriz de objeto contendo um número de outras matrizes interiores.

O seguinte loop for cria as matrizes interiores que são do tipo int [] usando a função NewIntArray() JNI. Se você só queria voltar para uma única matriz dimensional de inteiros, então a função NewIntArray() é o que você usaria para criar o valor de retorno. Se você quisesse criar uma única matriz dimensional de Cordas, em seguida, você pode usar a função NewObjectArray() mas com um parâmetro diferente para a classe.

Uma vez que você quiser retornar um array int, então o seu código vai ser algo como isto:

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;
}

Outras dicas

se alguém gostaria de saber como retornar String [] array:

código java

private native String[] data();

exportação nativa

JNIEXPORT jobjectArray JNICALL Java_example_data() (JNIEnv *, jobject);

código nativo

  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);  
  }  

de link: http://www.coderanch.com/t/326467/java/ java / Voltando-string-array-programa em Java

Com base na pergunta, isso já está explicado na primeira resposta que como podemos passar int [] via jobjectArray. Mas aqui está um exemplo de como podemos voltar a jobjectArray que contém listas de dados. Isso pode ser útil para situações como por exemplo: quando alguém precisa para retornar dados em formato 2D para desenhar alguma linha com x e y pontos. Os abaixo exemplo mostra como um jobjectArray pode retornar dados na forma de seguinte formato:

Entrada de Java ao JNI:
Array [Arraylist de pontos x flutuador] [Arraylist de pontos flutuantes y]

saída JNI para java:
jobjectArray [Arraylist de pontos x flutuador] [Arraylist de pontos flutuantes 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;

Uma solução simples é que escrever os dados de matriz em um arquivo de C, e, em seguida, acessar o arquivo de Java

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top