Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNI accessing array of array

I am trying to write a benchmark for different sorting algorithms in java, for that I wanted to explore the world of JNI. I am trying to sort a set of int arrays which are contained in an array. This is my Java header:

public static native void sort(int[][] c);

I used javah to generate this C header for it:

JNIEXPORT void JNICALL Java_org_jku_ssw_prsw2_ue6_jni_JNISorter_sort (JNIEnv *env, jclass cls, jobjectArray objArr)

Then I try to get the length of the array with

jsize len = (*env)->GetArrayLength(env, objArr);

but from here I'm kinda stuck, I can get a jobject element from this array using GetObjectArrayElement but how do I procceed from there to get a jint array which I can then finally sort?

like image 554
hille Avatar asked Feb 21 '26 19:02

hille


1 Answers

Since you know the jobject you retrieve is actually an int[], you can safely cast it to a jintArray and then go from there e.g.:

JNIEXPORT void JNICALL Java_Main_sort(JNIEnv *env, jclass _, jobjectArray objArr) {
    jsize len = (*env)->GetArrayLength(env, objArr);

    for(int i = 0; i < len; i++) {
        jintArray arr = (jintArray) (*env)->GetObjectArrayElement(env, objArr, i);
        jsize innerLen = (*env)->GetArrayLength(env, arr);
        jint* vals = (*env)->GetIntArrayElements(env, arr, NULL);            

        /* make changes to 'vals' */

        (*env)->ReleaseIntArrayElements(env, arr, vals, JNI_COMMIT);
        (*env)->DeleteLocalRef(env, arr);
    }
}
like image 183
Jorn Vernee Avatar answered Feb 23 '26 08:02

Jorn Vernee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!