Return a 2D primitive array from C to Java from JNI/NDK

后端 未结 3 1992
暖寄归人
暖寄归人 2020-12-16 03:21

I have found large amounts of documentation on how to generate a 2D primitive array in JNI and returning it to Java. But these pieces of information fail to describe how to

3条回答
  •  悲哀的现实
    2020-12-16 03:39

    I've made a simple function for conversion:

    jobjectArray getJNIArray(JNIEnv *env, jobject obj, const vector >& arr) {
        jclass floatClass = env->FindClass("[F"); //
        jsize height = arr.size();
    
        // Create the returnable 2D array
        jobjectArray jObjarray = env->NewObjectArray(height, floatClass, NULL);
    
        // Go through the first dimension and add the second dimension arrays
        for (unsigned int i = 0; i < height; i++) {
            jfloatArray floatArray = env->NewFloatArray(arr[i].size());
            env->SetFloatArrayRegion(floatArray, (jsize) 0, (jsize) arr[i].size(), (jfloat*) arr[i].data());
            env->SetObjectArrayElement(jObjarray, (jsize) i, floatArray);
            env->DeleteLocalRef(floatArray);
        }
    
        return jObjarray;
    }
    

提交回复
热议问题