Calling Native Windows DLL API with JNA

  1. Include the JNA library in your project
  2. Create an interface that extents com.sun.jna.Library with the prototypes of the functions your need to call
  3. Copy the DLL file to your project.
  4. Load the library (in this case dll) with com.sun.jna.Native
  5. Call the native functions with the interface create in 2.

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: '', name: 'jna', version: '5.6.0'

These code is shamelessly copy from 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.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

  • java/calling_native_windows_dll_api_with_jna.txt
  • Last modified: 2020/07/29 17:45
  • by chongtin