My linux world » Java – JNA

Java - JNA


Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using the Java Native Interface. JNA’s design aims to provide native access in a natural way with a minimum of effort. No boilerplate or generated glue code is required.
Wikipedia

Dependencies

If you use maven, add this to your pom.xml:

<dependency>
  <groupId>net.java.dev.jna</groupId>
  <artifactId>jna</artifactId>
  <version>${jna.version}</version>
</dependency>
 
<dependency>
  <groupId>net.java.dev.jna</groupId>
  <artifactId>jna-platform</artifactId>
   <version>${jna.version}</version>
</dependency>

Example

Define map the java interface to the native library interface :

public interface CLibrary extends Library 
{ 
  /**
   * If we are under windows, load msvcrt.dll, overwise load c library.
   */
  CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
 
  public int puts(String str);
 
  void printf(String format, Object... args);
}

And use it like this :

CLibrary.INSTANCE.puts("Hello World!");	    
CLibrary.INSTANCE.printf("Hello World!");

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.