You can add the jna.jar download from their official site in your project directly, or using gradle to add the dependencies like this.
. . dependencies { ... compile group: 'net.java.dev.jna', name: 'jna', version: '5.6.0' } . .
These code is shamelessly copy from https://stackoverflow.com/questions/492567/using-jna-to-link-to-custom-dll with little modification. Note that the function prototypes need to MATCH with the one defined in the DLL file! We load kernel32
, which is the file name of the dll in your project.
import com.sun.jna.Library; import com.sun.jna.Native; public class TestJNA { public interface Kernel32 extends Library { boolean Beep(int FREQUENCY, int DURATION); void Sleep(int DURATION); } public static void main(String[] args) { Kernel32 lib = (Kernel32) Native.load("kernel32", Kernel32.class); lib.Beep(698, 500); lib.Sleep(500); lib.Beep(698, 500); } }
Details of Kernel32 can be found in MSDN. We use Beep, and Sleep functions here. Note that we match out interfaces methods to those functions we called. Noted that Java, and C++ Type are different, and here are the mapping. JNA also support Linux platform.
BOOL Beep( DWORD dwFreq, DWORD dwDuration ); void Sleep( DWORD dwMilliseconds );