3

I want to pass the following pointer array through the JNI layer from C code

char *result[MAXTEST][MAXRESPONSE] = {
    { "12", "12", "" },
    { "8",  "3",  "" },
    { "29", "70", "" },
    { "5",  "2",  "" },      
    { "42", "42", "" }
};

In java code I have written the following declaration

public static native String[][] getResult();

I am confused how to pass that array through JNI layer to Java code??? Following is the JNI layer description

JNIEXPORT jobjectArray JNICALL Java_com_example_CheckResult_getResult
  (JNIEnv *env, jclass thiz) {
Confused over here ????
}
AndroidDev
  • 2,627
  • 6
  • 29
  • 41
  • 1
    This is a duplicate of http://stackoverflow.com/questions/6070679/create-populate-and-return-2d-string-array-from-native-code-jni-ndk – jop Apr 12 '13 at 14:01
  • While you *can* do so (you essentially have to create multiple Java objects, including arrays, arrays as array elements, and strings), I'd recommend that you re-think your interface to instead return a single block of data (maybe a single `byte` buffer with NUL terminators between strings) and let the Java side re-interpret it if necessary. The general complexity of turning a multi-dimensional C array in JNI into a multi-dimensional Java array is a lot higher than constructing the multi-dimensional array on the Java side (assuming that your *really* need that format) from simpler data. – technomage Apr 12 '13 at 16:17

1 Answers1

2

Finally after hours working on jop's shared link, I could solve my problem. The code goes as below:

JNIEXPORT jobjectArray JNICALL Java_com_example_CheckResult_getResult(JNIEnv *env, jclass thiz) {
    jboolean flag = JNI_TRUE;
    jclass stringClass = (*env)->FindClass(env, "java/lang/String");
    jobjectArray row;
    jobjectArray rows;

    jsize i, j;
    for(i=0; i<5; i++) {
        row = (*env)->NewObjectArray(env, MAXRESPONSE, stringClass, 0);
        for(j=0; j<3; j++) {
            (*env)->SetObjectArrayElement(env, row, j, (*env)->NewStringUTF(env, userResponse[i][j]));
        }

        if(flag == JNI_TRUE) {
            flag = JNI_FALSE;
            rows = (*env)->NewObjectArray(env, MAXTEST, (*env)->GetObjectClass(env, row), 0);
        }

        (*env)->SetObjectArrayElement(env, rows, i, row);
    }

    return rows;
}
Community
  • 1
  • 1
AndroidDev
  • 2,627
  • 6
  • 29
  • 41