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 ????
}
2
  • 1
    This is a duplicate of stackoverflow.com/questions/6070679/… Commented Apr 12, 2013 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. Commented Apr 12, 2013 at 16:17

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.