JNA Example

0

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.

		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>jna</artifactId>
			<version>4.4.0-1</version>
			<scope>compile</scope>
		</dependency>

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

YourOwnLibraryMapping:

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.

JnaExample:

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);
        System.out.println(libraryMapping);
        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.
Output:

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
Share.

Comments are closed.