Java Native Access - Example

Example

The following program loads the local C standard library implementation and uses it to call the printf function.

Note: The following code is portable and works the same on Windows and Linux / Unix / Mac OS X platforms.

import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Platform; /** Simple example of native library declaration and usage. */ 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); } } }

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", 0777); 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); } }

Read more about this topic:  Java Native Access

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)