recipe № 001

running simple JNI code

In this sample we will create few source files, Java class file and the library. After you finish this tutorial, you should end up with layout like this

To get simple JNI sample running we need few elements. First, we need to create Java class that will call native code. In this sample we will use HelloWorld.java. Make sure to store it inside recipeNo001/HelloWorld.java. The package is recipeNo001 and class is HelloWorld.
Pay attention to System.loadLibrary method. It loads native code into JVM. As you can see it is declared in static block of HelloWorld class. It means that this code will execute priori to creation of any object of this class. This way, we can ensure that library is already loaded before we try to make any call to native code.

Basically, what we want to do here looks like this

helloworld001

After class is ready, we can compile it. Then, we can create native’s code interface. Compilation is done with javac command and creation of native interface is done using javah command. To make layout of the sources more transparent, I am putting C codes inside c directory and Java codes inside java directory. Let’s compile the code.

After this call we will create a C header file that contains method signature. This file will be created inside c directory

To get everything working we have to provide implementation of this method. When HelloWorld class will call it’s displayMessage() method, it will actually call native code with signature Java_recipeNo001_HelloWorld_displayMessage. So, we need to implement it.

I have provided implementation of the method inside recipeNo001_HelloWorld.c. As you can see it’s very simple code. It just prints something.

To get it working with Java, we have to create shared library. In this sample we are using OS X based format. To create library you have to compile the code and create shared library using cc.

This will produce shared library libHelloWorld.dylib. Pay attention to the fact that loadLibrary takes only name of the library as argument. Java will properly create proper library file name. In case of OS X it will be libHelloWorld.dylib in case of Linux it will be libHelloWorld.so. After library is created, we can run the code.

As you can see, we can read what native code writes to stdout. And that’s what we wanted to get.