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:
- Download and install NetBeans.
- Download the project file, it is unpacked into the JNA directory.
- Download the jna.jar library on Sun's site and copy it into the JNA directory.
- Load the project in NetBeans from this directory.
- Add jna.jar to the list of libraries:
Project Properties -> Libraries -> Add JAR / Folder. - 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
- Java Native Access. The site of Sun provide the jna.jar library.
- NetBeans. Java IDE.
Download
- Simple demonstration.
This demo displays a simple text using the puts function of the C language. A project file for NetBeans is included.
(c) 2008-2009 Scriptol.com