JNA Example


Java Native Access (JNA) is an open source library that provides Java programs easy access to native shared libraries.
The JNA library uses a small native library called foreign function interface library (libffi) to dynamically invoke native code.
In this example we will see a glimpse of how the method calls gets mapped to the function defined in shared library. We will see how we can map printf() to the target native method.

We need to first define our own interface that contains the methods which in turn get mapped to one of the corresponding native function names.

JNA Dependency

Add the below dependency to your pom.xml.


The user defined interface must extend com.sun.jna.Library.


package com.javarticles.jna;

import com.sun.jna.Library;

public interface YourOwnLibraryMapping extends Library {
    void printf(String format, Object... args);

Load the library and this should return a proxy to the above defined interface.


package com.javarticles.jna;

import com.sun.jna.Native;

public class JnaExample {
    public static void main(String[] args) throws InterruptedException {
        YourOwnLibraryMapping libraryMapping = (YourOwnLibraryMapping) Native.loadLibrary("msvcrt", YourOwnLibraryMapping.class);
        libraryMapping.printf("Jna %s", "Example");

As you can see below the library instance returned is a proxy object which maps the methods declared to native library msvcrt.dll.

Proxy interface to Native Library <[email protected]>
Jna Example

Download the Source code

This was an example about Java JNA.

You can download the source code here: jnaExample.zip

Comments are closed.