Array handling (mainly a synchronization problem)

Java declarations are as follows:


    public native void giveArray(int[] array);
Copy the code

C code is as follows:


// Collation rules, smaller first
int compare(int *a, int *b) {
    return (*a) - (*b);
}
/ / the incoming
JNIEXPORT void JNICALL Java_com_haocai_jni_JniTest_giveArray
(JNIEnv *env, jobject jobj, jintArray arr) {
    //qsort();
    //jintArray -> jint pointer ->c int array
    jint *elems = (*env)->GetIntArrayElements(env, arr, NULL);

    // The length of the array
    int len = (*env)->GetArrayLength(env, arr);

       / / sorting
    qsort(elems,len,sizeof(jint), compare);

    //C operations are synchronized to Java and resources are freed
    (*env)->ReleaseIntArrayElements(env, arr, elems, 0);

}
Copy the code

Finally, test in Java:.


    public native void giveArray(int[] array);

    public static void main(String[] args) {
 
        JniTest jniTest = new JniTest();
        int[] array = {100.3.10.7.5.103.160.79.51};
        jniTest.giveArray(array);
        for(inti : array){ System.out.println(i); }}Copy the code

Result output:

3, 5, 7, 51, 79, 100, 103, 160Copy the code

Note:

  • Call GetIntArrayElements to get a pointer to the C array before processing the C array.
  • ReleaseIntArrayElements after C gets the Java array to operate on or modify it, it needs to call ReleaseIntArrayElements to update it.

The final argument to this method is the mode:

model role
0 Java arrays are updated, and C/C++ arrays are freed.
JNI_ABORT Java arrays are not updated, but C/C++ arrays are freed.
JNI_COMMIT Java arrays are updated without freeing C/C++ arrays (arrays are still freed after the function is executed).

C code is as follows:


JNIEXPORT jintArray JNICALL Java_com_haocai_jni_JniTest_getArray
(JNIEnv *env, jobject jobj, jint len) {

    // Create an array of the specified size
    jintArray jint_arr = (*env)->NewIntArray(env, len);
    jint *elems = (*env)->GetIntArrayElements(env, jint_arr, NULL);

    int i = 0;
    for (; i < len; i++) {
        elems[i] = i;
    }


    
    (*env)->ReleaseIntArrayElements(env, jint_arr, elems, 0);

    return jint_arr;
}
Copy the code

Finally, test in Java:.


    public native void giveArray(int[] array);

    public static void main(String[] args) {
 
        JniTest jniTest = new JniTest();
        int[] array2 =  jniTest.getArray(5);
        for(inti : array2){ System.out.println(i); }}Copy the code

Result output:

0, 1, 2, 3, 4Copy the code

(*env)->ReleaseIntArrayElements(env, jint_arr, elems, JNI_COMMIT);
Copy the code

Result output:

0, 1, 2, 3, 4Copy the code

(*env)->ReleaseIntArrayElements(env, jint_arr, elems, JNI_ABORT); Or comment that lineCopy the code

Result output:

0, 0, 0, 0Copy the code