recipe № 011

passing primitive types from C to Java

In this sample, we will pass all primitive types from C to Java. Mapping between types follows:

After you finish this part of tutorial, you should end up with directory structure similar to one below.

First of all, we need a Java class that will call native code. In this case we will introduce few changes. First of all, library will contain few native functions. Till now, each function was implemented as a separate shared library. This time, all functions will go into single library.

As you can see, we are expecting different results from different functions. For each primitive type we have one function.

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

After this call, header is created

Note, that this time, we don’t have anything else apart from JNIEnv * and jclass as function call. This time, we don’t pass anything from our Java code. We only expect various results (in terms of the result’s type).

Now, we can generate implementation of the function. Pay attention to the code.

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 produced on the stdout string that was declared inside C.