3

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?

1 Answer 1

4

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

3 Comments

Tha'ts not a cast, it is a function call.
@EJP What do you mean? The jintArray arr = (jintArray) ... uses a cast.
You probably should add a ( *env )->DeleteLocalRef( env, arr ); call at the end of your for loop. With a large object array, you might fill the local reference table. See stackoverflow.com/questions/24289724/…

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.