Create, populate and return 2D String array from native code (JNI/NDK)

前端 未结 1 2018
-上瘾入骨i
-上瘾入骨i 2021-01-06 19:22

I\'m finding this particular bit of code quite difficult (Not least of which because I only started playing with C a week ago).

I\'ve been trying hard to find the ri

相关标签:
1条回答
  • 2021-01-06 20:10

    To get a jclass for the row type, you can call GetObjectClass() on one of the rows. This works:

    Main.java

    public class Main {
    
        static {
            System.loadLibrary("mynative");
        }
    
        private static native String[][] getStringArrays();
    
        public static void main(String[] args) {
            for (String[]  array : getStringArrays())
                for (String s : array)
                    System.out.println(s);
        }
    }
    

    mynative.c

    static jobjectArray make_row(JNIEnv *env, jsize count, const char* elements[])
    {
        jclass stringClass = (*env)->FindClass(env, "java/lang/String");
        jobjectArray row = (*env)->NewObjectArray(env, count, stringClass, 0);
        jsize i;
    
        for (i = 0; i < count; ++i) {
            (*env)->SetObjectArrayElement(env, row, i, (*env)->NewStringUTF(env, elements[i]));
        }
        return row;
    }
    
    JNIEXPORT jobjectArray JNICALL Java_Main_getStringArrays(JNIEnv *env, jclass klass)
    {
        const jsize NumColumns = 4;
        const jsize NumRows = 2;
    
        const char* beatles[] = { "John", "Paul", "George", "Ringo" };
        jobjectArray jbeatles = make_row(env, NumColumns, beatles);
    
        const char* turtles[] = { "Leonardo", "Raphael", "Michaelangelo", "Donatello" };
        jobjectArray jturtles = make_row(env, NumColumns, turtles);
    
        jobjectArray rows = (*env)->NewObjectArray(env, NumRows, (*env)->GetObjectClass(env, jbeatles), 0);
    
        (*env)->SetObjectArrayElement(env, rows, 0, jbeatles);
        (*env)->SetObjectArrayElement(env, rows, 1, jturtles);
        return rows;
    }
    

    Building, error handling omitted for clarity.

    0 讨论(0)
提交回复
热议问题