recipe № 014

passing memory allocated in C back to Java

In this sample, we will pass arrays created (allocated) inside C back to Java.

To get the feeling of how to pass arrays from Java to C, take a look at recipe № 012. If you want to take a look at how to pass arrays into C and modify them, take a look here: recipe № 013.

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 allocate given number of elements. After elements are allocated, they will be returned back to Java.

As you can see, we are passing size of the array into each function. Every native method will create appropriate array and pass it back to Java.

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

After this call, header is created

Note, that each function has the same parameter but different return type. You can find different return types: jdoubleArray, jfloatArray, jlongArray, jintArray, jshortArray, jcharArray, jbyteArray, jbooleanArray.

Now, we can generate implementation of the functions. Pay attention to the code. In each function we do the same thing. Reserve object that will be passed back to Java, allocate memory in C, copy data and free memory region inside C.

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 allocated and filled with data inside C.