Calling C code from Java using JNA

I recently wrote an article about calling C code from Java using JNI. Another way to call C code from Java is to use Java Native Access, which makes things significantly easier.

First off, we'll need to write the C library. Create a ctest.c file containing a simple helloFromC function:

/* ctest.c */

#include <stdio.h>

void helloFromC() {
    printf("Hello from C!\n");

Notice that this version is much simpler than the JNI version, and also not intrusive at all. Using JNA you can run code from any library without any of the additional boilerplate associated with JNI.

Now that we have the C source, let's create a library:

gcc -o -shared ctest.c

This is the standard way of creating a library, not specific to Java in any way. For details about creating the library on Mac or Windows, see the previously mentioned article.

Let's now write the Java code in a file:

/* */

import com.sun.jna.Library;
import com.sun.jna.Native;

public class HelloWorld {
    public interface CTest extends Library {
        public void helloFromC();
    static public void main(String argv[]) {
        CTest ctest = (CTest) Native.loadLibrary("ctest", CTest.class);

After downloading the JNA package from the official Subversion repository an placing it in the same directory, we can now compile the Java application:

javac -classpath jna.jar

This should produce a HelloWorld.class file containing our compiled class. We can run it with:

java -classpath jna.jar:. HelloWorld

If everything works correctly, you should see:

Hello from C!