recipe № 013

passing primitives array from Java to C and back

In this sample, we will pass all primitive types from Java to C. This time, we will pass them inside arrays and for some of them we will change values of elements inside array that is visible in Java. For rest of them, we will reject changes done inside C code.

To get the feeling of how to pass arrays from Java to C, take a look at recipe № 012.

In here, we will use JNI_COMMIT and JNI_ABORT values as last argument of (*env)->ReleaseBooleanArrayElements(env, array, body, mode)

Release[PrimitiveType]ArrayElements can take one of three different values as last argument (mode):

The schema for the call follows:

Later on, you can read the explanation for all the primitive types.

After you finish this sample, you should came up with structure similar to one below:

First of all, we need a Java class that will call native code. In this case, library will contain few native functions. Each function will print given inputs. All of the native functions will be packed inside single library file.

As you can see, we are passing each array into separate function and then, we print results that came back from C.

Again, we have to compile the class and create native’s code header.

After this call, header is created

Note, that each function has a different parameter’s type. You can find there: jdoubleArray, jfloatArray, jlongArray, jintArray, jshortArray, jcharArray, jbyteArray, jbooleanArray.

Now, we can generate implementation of the functions. Pay attention to the code. This time, we will use JNI_COMMIT for some of the functions and JNI_ABORT for the others. This way, only part of the changes will be visible in Java.

Compilation is plain and simple

After all elements are in place, all we have to do is to run the sample

As you can see, Java code shows that some of the arrays were updated while others remained unchanged.