Java Native Access (JNA) ist eine Java-Programmbibliothek für den Zugriff auf plattformspezifische ("native") dynamische Programmbibliotheken (DLL in Windows). Hierbei muss im Unterschied zu JNI kein plattform-spezifischer Code geschrieben werden.
JNA ist in der Funktion mit den .NET Platform Invocation Services (P/Invoke) vergleichbar. Es unterstützt eine automatische Umwandlung zwischen einigen C- und Java-Datentypen. Die erforderliche Java-Mindestversion ist 1.4.
Lizenz
LGPL Version 2.1 oder höher.
Anwendungen
Die folgenden Softwareprojekte verwenden JNA:
Beispiel
Das folgende Beispiel lädt die Standard C Library um die printf-Funktion aufzurufen. Dieses Beispiel funktioniert auf Microsoft Windows und Linux / Unix / Mac OS X.
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
/** Einfaches Beispiel einer Deklaration und Nutzung einer Dynamischen Programmbibliothek. */
public class HelloWorld {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary)
Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
CLibrary.class);
void printf(String format, Object... args);
}
public static void main(String[] args) {
CLibrary.INSTANCE.printf("Hello, World\n");
for (int i=0;i < args.length;i++) {
CLibrary.INSTANCE.printf("Argument %d: %s\n", i,
args[i]);
}
}
}
The following program loads the C POSIX library and uses it to call the standard mkdir function.
Note: The following code is portable and works the same on POSIX standards platforms.
import com.sun.jna.Library;
import com.sun.jna.Native;
/** Simple example of native C POSIX library declaration and usage. */
public class exampleOfPOSIX {
public interface POSIX extends Library {
public int chmod(String filename, int mode);
public int chown(String filename, int user, int group);
public int rename(String oldpath, String newpath);
public int kill(int pid, int signal);
public int link(String oldpath, String newpath);
public int mkdir(String path, int mode);
public int rmdir(String path);
}
public static void main(String[] args) {
POSIX posix = (POSIX) Native.loadLibrary("c", POSIX.class);
posix.mkdir("/tmp/newdir", 777);
posix.rename("/tmp/newdir","/tmp/renamedir");
}
}
The program below loads the Kernel32.dll and uses it to call the Beep and Sleep functions.
Note: The following code works only on Windows platforms.
import com.sun.jna.Library;
import com.sun.jna.Native;
/** Simple example of Windows native library declaration and usage. */
public class BeepExample {
public interface Kernel32 extends Library {
// FREQUENCY is expressed in hertz and ranges from 37 to 32767
// DURATION is expressed in milliseconds
public boolean Beep(int FREQUENCY, int DURATION);
public void Sleep(int DURATION);
}
public static void main(String[] args) {
Kernel32 lib = (Kernel32) Native.loadLibrary("kernel32",
Kernel32.class);
lib.Beep(698, 500);
lib.Sleep(500);
lib.Beep(698, 500);
}
}
Weblinks
- Java Native Access Homepage (Englisch)