JNA

Java Native Access is an extension to Java that allows the use of native APIs by including dynamically library files, DLLs under Windows.

JNA is a simpler alternative to JNI which does not require to generate code for using C functions. To use them, simply include the file that defines them and declare the header of these functions in an interface.

Demonstration

To use the puts function of the C language, which is provided by the msvcrt.dll file in Windows, create the following interface:

package CInterface; 
       
import com.sun.jna.Library; 
       
public interface CInterface extends Library 
{ 
      public int puts(String str);
}     

We have declared the CInterface interface which is a subclass of JNA.
Inside the interface, C functions are declared as methods. To use the method puts simply create an instance of CInterface:

 CInterface demo = (CInterface) Native.loadLibrary(libName, CInterface.class); 
 demo.puts("Hello World!");

For this to work, some imports are required:

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

In addition, the library jna.jar must be included in the project.

A complete project for NetBeans can be downloaded. It contains two sources:
- CInterface.java that holds the interface above.
- Hello.java that uses this interface.

To run the demonstration:

  1. Download and install NetBeans.
  2. Download the project file, it is unpacked into the JNA directory.
  3. Download the jna.jar library on Sun's site and copy it into the JNA directory.
  4. Load the project in NetBeans from this directory.
  5. Add jna.jar to the list of libraries:
    Project Properties -> Libraries -> Add JAR / Folder.
  6. Compile the project.

Then type the command:

java -jar /jna/dist/hello.jar "My own text!"

You can add the interface to all the functions you need, if they are present in the same DLL, and create an interface for each DLL file to include.

Ressources

Download

Programming technologies Ajax - API - Cassandra - CIL - CLI - Cookie - Cover Flow - Dalvik - DFA - .NET - HTTP code - IDE - JavaFX - JNA - JSON - MySQL - NaCl - Protocol Buffers - Qt - REST - Servlet - Web 2.0 - WebGL - Webkit - WYSIWYG

(c) 2008-2009 Scriptol.com