Java JNA sample: How to wrap your c code

Imagine you have some c-code myLib.c that provides a function like this:

int foo(int bar):

and a header file myLib.h like this:

extern int foo(int bar);

to make this function available to java, you have 2 options, whether to use JNI, what requires to build the library with a specific header, generated from your java class, so you cannot just use any library without rebuilding it.
Or you can use JNA, which is quite a bite simpler to use, because it doesn’t require to rebuild a specific library.
You can download the library here.The mapping in JNA is done by extending an interface named Library,

public interface myLib extends Library {

myLib INSTANCE = (myLib) Native.loadLibrary(“myLib”, myLib.class);
int foo(int bar);


to make shure the jvm can find your library, the system property “jna.library.path” has to point to it’s absolut location.

static {
System.setProperty(“jna.library.path”, “/some/absolut/path”);

on unix-based systems, or

static {
System.setProperty(“jna.library.path”, “C:\some\absolut\path”);

on windows systems instead. You can check the underlying os with:


or accordingly for other common operating systems.

Now your native function-call, here foo(int bar) is callable on the the INSTANCE of your native library.

in java:

int a =; 


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: