How to call/invoke external DLL library method/function from Java code?


Java’s JVM allows you to do many smart things but sometimes you may be forced to directly use external library or writing code in pure java would be very time-consuming comparing it with something more low-leveled. I stumbled upon such a problem and had to use a .dll driver from a hardware provider. Of course I googled it and didn’t find much info, and what I’ve found  mostly concerned about JNI (Java Native Interface). I would like to tell you about JNA which is fast and simple to use in aforementioned task.

So, how does it work? The only thing you have to do is to download and import JNA (Java Native Access) to your project and write a simple class.
Hereunder you can analyse a simple Java program which uses a sample .dll. You can download my java code and .dll library sources later.

Java code:

package jnahelloworldtest;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Platform;
import com.sun.jna.*;

/** Simple example of native library declaration and usage. */
public class Main {
    public interface simpleDLL extends Library {
        simpleDLL INSTANCE = (simpleDLL) Native.loadLibrary(
            (Platform.isWindows() ? "simpleDLL" : "simpleDLLLinuxPort"), simpleDLL.class);
		// it's possible to check the platform on which program runs, for example purposes we assume that there's a linux port of the library (it's not attached to the downloadable project)
        byte giveVoidPtrGetChar(Pointer param); // char giveVoidPtrGetChar(void* param);
        int giveVoidPtrGetInt(Pointer param);   //int giveVoidPtrGetInt(void* param);
        int giveIntGetInt(int a);               // int giveIntGetInt(int a);
        void simpleCall();                      // void simpleCall();

    public static void main(String[] args) {

        simpleDLL sdll = simpleDLL.INSTANCE;

        sdll.simpleCall();  // call of void function

        int a = 3;
        int result1 = sdll.giveIntGetInt(a);  // calling function with int parameter&result
        System.out.println("giveIntGetInt("+a+"): " + result1);

        String testStr = "ToBeOrNotToBe";
        Memory mTest = new Memory(testStr.length()+1);  // '+1' remember about extra byte for \0 character!
        mTest.setString(0, testStr);
        String testReturn = mTest.getString(0); // you can see that String got properly stored in Memory object
        System.out.println("String in Memory:"+testReturn);

        Memory intMem = new Memory(4);  // allocating space
        intMem.setInt(0, 666); // setting allocated memory to an integer
        Pointer intPointer = intMem.getPointer(0);

        int int1 = sdll.giveVoidPtrGetInt(Pointer.NULL); // passing null, getting default result
        System.out.println("giveVoidPtrGetInt(null):" + int1); // passing int stored in Memory object, getting it back
        int int2 = sdll.giveVoidPtrGetInt(intMem);
       //int int2 = sdll.giveVoidPtrGetInt(intPointer);  causes JVM crash, use memory object directly!
        System.out.println("giveVoidPtrGetInt(666):" + int2);

        byte char1 = sdll.giveVoidPtrGetChar(Pointer.NULL);  // passing null, getting default result
        byte char2 = sdll.giveVoidPtrGetChar(mTest);        // passing string stored in Memory object, getting first letter

        System.out.println("giveVoidPtrGetChar(null):" + (char)char1);
        System.out.println("giveVoidPtrGetChar('ToBeOrNotToBe'):" + (char)char2);


Mappings table

Not every native type maps directly to Java type, furthermore a class representing pointers had to be introduced.  You can read a handy type mapping table below:

Native Type Size Java Language Type Common Windows Types
char 8-bit integer byte BYTE, TCHAR
short 16-bit short short WORD
wchar_t 16/32-bit character char WCHAR, TCHAR
int 32-bit integer int DWORD
int boolean value boolean BOOL
long 32/64-bit integer NativeLong LONG
long long, __int64 64-bit integer long
float 32-bit FP float
double 64-bit FP double
char* C string String LPTCSTR
void* pointer Pointer LPVOID, HANDLE, LPXXX


  • DLLVisual Studio source project – ready to use Visual Studio 2010 project. You can alter it to continue experimenting with invoking DLL methods of library attached to the Netbeans project.
  • Netbeans project – ready to use NetBeans 6 project using example code explained in this article with appropriate jars and DLL library attached
  • JNA library jars – link to official JNA libraries download page

Useful links:

DLL library C++ functions source :

#include "simpleDLL.h"

#include <stdexcept>

using namespace std;

namespace simpleDLLNS
    char simpleDLL::giveVoidPtrGetChar(void* param)
        if(param != 0)
		char* paramChrPtr = (char*)param;
		return *paramChrPtr;
			return 'x';


	int simpleDLL::giveIntGetInt(int a)
		return 2*a;

	void simpleDLL::simpleCall(void)
		int x = 3;

	int simpleDLL::giveVoidPtrGetInt(void* param)
			int* x = (int*)param;
			return *x;

			return -1;



  • […] of Memory and Pointer JNA objects. Example covering such case is provided in my another article: How to call/invoke external DLL library method/function from Java code? JNA, Java, Programmingjava, JNA, native code ← How to call/invoke external DLL library […]

  • Thank you soo much. took me a WHOLE day to find this post. Lots of examples of using JNA but none that shows exactly how it will be done in Real Life. you Polish guys are amazing! Dzienki! Will call u for beer when I come to poland next time!

    • hahaha, thank you for appreciating my content. I’ll keep your word about the beer, but linking me will be also good for now in favour 🙂

  • Did u see that I posted this article on dzone? Check here

    You should have more hits today….lol

    • didn’t check my stats today. thank you very much! 😉
      nice news about javaFX redist btw, thought there’s no hope about it

  • Hi Michal

    This is the best one page example of using JNA I have found so far. Got me started in about 5 minutes, regretfully, I got stuck in next 5 minutes 🙁 🙁

    Here are immediate 2 issues:
    (1) Does JNA handle mangled names? What I have is the DLL and the interface definition (ie. header files). The problem is that the function defined as
    int* func(int) is mangled to int* _func@4(int) and Java does not like the ‘@’ in the name of the method.

    (2) Callbacks. The native lib uses them all over the place. In C++ it is easy. DLL provides the interface to define callbacks, so all the app has to do is to create them and pass the pointer to the API. When the event which has the associated callback occurs, the C++ app gets the information. Can something the same be done between the app written in Java and the DLL?

  • I am new to Java and I find using the compact style documentation like those two a bit difficult, hence my search for sample code.

    I looked at some callback samples and I do not see how I can bind my own callback method (written in Java) with the DLL. All I have in the DLL is the API to specify the callback by feeding in the pointer to the callback function. Does this mean that the callback must be a C function?

    • I’m not sure I fully understand you. Are you trying to invoke Java class method from native library passing this Java method as a Callback? I didn’t deal seriously with callbacks in Java although this looks like interesting discussion about your problem
      Callbacks in Java JNA :

      Was link about solving problems with Mangled names in JNA helpful for you?

  • Hi there,

    I am new to accessing DLLs from Java using JNA. I need to access a methods from a class within the DLL and can not do this by just calling the library as I can seem to work out how to access a class I.e. the DLL is called CDrawControl.dll, but the class within the DLL I need to access is DrawCtl. So I need to get and instance of the DrawCtl class.
    So all in all, how to I reach this method in the DLL?

    ie CDrawControl.DrawCtl.SaveFile()

    It is probably something very simple I am missing.Thanks for your help in advance!!!

    • I have only tried JNA with direct functions mapping, I am not really sure if what you need to do is possible using JNA or maybe you have to use JNI.. Official JNA documentation is now here: Please let me know if you solve your problem, it’s interesting 😉

  • Hi Michal,

    Nice job, simple strait example for JNA utilization, thanks for your effor, easing ours 😉
    I am trying to demo run your samle program, I am through most of the hurdles (configuring library path, various java.lang.UnsatisfiedLinkError), Now struck at error “Unable to load library ‘simpleDLL’: The specified module could not be found.” please guide me through this abt how to resolve this.

    Regards, Mithun PG

    • Hi Even I am also getting the same error “module could not be found” if you found the solution please let me know.

  • Hi there and thanks for an excellent tutorial. There seems to be one “bug” in that the “unsatisfiedlinkerror” that I also get may be related to the missing file MSVCR100D.dll, see this link on how to integrate the file statically at compile time: I used the utility DEPENDENCY WALKER to detect this. So Visual Studio must either be installed, or linked in. -Carl

  • Greats, but I have is error Exception in thread “main” java.lang.UnsatisfiedLinkError: Unable to load library ‘simpleDLL’ and the library is the current folder.

  • Not sure what I’m doing wrong. Have an even simpler example. Can’t find the methods at runtime. Is there any problem using Netbeans / mingw compiler?

    QnAudio.cpp, compiled to a dll which is found by the java program:

    #include “QnAudio.h”

    using namespace std;

    namespace QnAudioNS

    int QnAudio::getData(int i) {
    return data[i];

    void QnAudio::setData(int i, int input) {
    data[i] = input;

    Guts of the java program:

    public class NewFrame extends java.awt.Frame {

    public interface QnAudio extends Library {
    QnAudio INSTANCE = (QnAudio) Native.loadLibrary(
    “C:/Documents and Settings/Al Gerheim/My Documents/NetBeansProjects/QnAudio/dist/Debug/MinGW_TDM-Windows/libQnAudio”,
    // “libQnAudio”,

    int getData(int i);
    void setData(int i, int input);

    public static void main(String args[]) {

    QnAudio qn_Audio = QnAudio.INSTANCE;

    qn_Audio.setData(0, 1); // error at this statement, function not found.
    qn_Audio.setData(1, 5);
    qn_Audio.setData(2, 10);

    int i = qn_Audio.getData(0);
    i = qn_Audio.getData(1);
    i = qn_Audio.getData(2);
    i = 1000;


  • HI i am getting the following exception when invoking the external DLL file.

    Exception in thread “main” java.lang.UnsatisfiedLinkError: Unable to load library ‘C:/Users/kumargud/Desktop/JNA/simpleDLL/’: The specified module could not be found.

  • Hi,
    i have a c dll method in which the function signature is: int func(HANDLE handle, char *Info);
    The parameter [out]Info is an output parameter. Could you let me know how to call this function. I tried using Callback in jna but not able to get the proper value of info.
    I m using jna to call this function.

  • Hello! Did you try to run this with 64-bit DLL? Weird, because I can’t transmit parameter from java code to C method (in dll), but I can get the return value in java code from dll methods.

  • The result is the same, with different value of parameter a. I also modified code for giveIntGetInt function to see what I got in this parameter, an in output file I always see “-2147393078”.

    int simpleDLL::giveIntGetInt(int a)
    //a = 22;
    FILE *stream;
    if ((stream = fopen(“g:\\TEST.dat”, “wt “)) == NULL)
    return 0;
    fprintf (stream, “%d\n”,a);

    return 10*a;

  • Thank you very much for the post , it is very simple and informative.
    I downloaded the project and trying to run it is giving me the below error tired copying in build/classes and clean the build and try to run the project but dint help, please guide.

    Exception in thread “main”
    java.lang.UnsatisfiedLinkError: Unable to load library ‘simpleDLL’: The specified module could not be found.

    • This means that JNI can’t find the DLL-file.

    • See this link

      • I am also facing the same problem. Unsatisfiedlinkerror. Please help me. Where to place the dll. I am using netbeans and I also tried to use djava.lib.path in vm options but still no solution available.

        • Maybe your ‘project home’ dir isn’t where you think it’s. Maybe try adding some code creating disk file in ‘relative path’ to my sample and determine this way where java looks for your file?

  • can any one pls explain the code clearly in java with dll….how to load the dll file and how to access the function in dll…

  • JNI cant find the dll-file, why is that? i just unpacked your test project an a error occours 🙁

    Could you help me figure out this problem? Shoudlnt it work when i import your project and run it ?

  • Thanks for this post. For unable to load library error – just add newly created dll in project workspace library. Although it seems to be older post I think future users might benefit from this suggestion.

  • Hi Michal, i tried your project & it worked well for me.
    But now in same your project I made chanegs to use my dll- & its not working. Its not able to find the functin that i am trying to call from the dll file–any suggestions?
    i am getting this error –
    Exception in thread “main” java.lang.UnsatisfiedLinkError: Error looking up function ‘getmultiplication’: The specified procedure could not be found.

    at com.sun.jna.Function.(
    at com.sun.jna.NativeLibrary.getFunction(
    at com.sun.jna.NativeLibrary.getFunction(

  • HI There,
    Great Job!
    Just Curious to ask, Why we do use .def for specifying methods?


  • Hello michal,

    i want to write a program in java that can display how many keys are pressed by user in frame or outside System java frame to do that i have to use systems dll files and i have no idea about how to use system dll file i’m stuck to find anything related to this on internet…. but i read your post it’s kind of interesting it help me to understand what is dll file is all about and know i have a little idea about them and how to use them

    but will you please give me any suggestion or help for my program because i’m new to dll files and i have no idea so please tell me anything that you know about this… Thanks in Advance

  • I don’t know what was the last time (dates next to comments are not working in FF), that you received some gratitude, so I’m expressing mine: very good article. It gave me a quick and efficient stab at a dll. Thanks!

    • I am glad it helped you 🙂

  • I want to access a functions in c++ dll provided by vendor. I have the method signatures with me. Please guide me to use them in java.

  • I downloaded and opened your netbeans project. I too got the same error many others are reporting…
    Exception in thread “main” java.lang.UnsatisfiedLinkError: Unable to load library ‘simpleDLL’: The specified module could not be found. Please explain what to do in simple english. Thanks.

    • I also tried adding
      as the first line in public static void main(
      and got the following new error
      “Exception in thread “main” java.lang.UnsatisfiedLinkError: C:\Users\Greg\Documents\NetBeansProjects\JNAHelloWorld\simpleDLL.dll: Can’t find dependent libraries” which tells me it is finding simpleDLL.dll (because that is the correct location) but that there must be dependent libraries that simpleDLL.dll is referencing that can’t be found.

  • Hello Michal,

    i know this is a very old post. but your post really helped me .. i thank you for that .

    I m stuck somewhere but .. I an trying to access a 3rd party dll. The problem is the functions/methods in that dll are inside the classes of the dll.

    So how to access them with this hierarchy ???

    Please help

  • Hello,

    how do I handle in/out Parameter
    for following in C++ function
    void getString(LPTSTR receiv) {
    receiv = “Hello”;
    in Java it it doesn’t work with
    void getString(String receive)

    • Maybe try with pointer types?

  • Hi, great post! I just need a very basic clarification. I have a .dll file at some file system location. I am running my java code to make calls to dll methods in eclipse. Now how would Native.loadLibrary() pick the exact location of my .dll file? And is it mandatory that my java interface and the .dll file have the same name(in your example it is “”simpleDLL”)? My question might be really naive but please help me out here.

    • Confronting the Javadoc : “Library Search Paths A search for a given library will scan the following locations:

      jna.library.path User-customizable path
      jna.platform.library.path Platform-specific paths”

      BTW you should be aware that newer versions of JNA are available now on GitHub, I see they also have examples there now, so maybe it will help you.

      • Thanks very much. I will check that out.

  • Also to add on, I tried the sample code and I get unsatisfiedLinkError. I have placed the .dll file in the directory path specified in PATH System Environment variable. Still I face this issue. What could be the problem?

  • for all those getting the “Unable to load library” error, it might be because your IDE is pointing to the 64bit JDK and the simpleDLL is 32bit.

    i resolved this by pointing my project to the 32bit JDK in netbeans.

    Properties -> Libraries -> Manage Platforms -> Add Platform

    • I’m NetBeans IDE 7.31. My Properties>Libraries>Manage Platforms already points to 32bit java (C:\Program Files (x86)\Java\jdk1.7.0_25) but sill have same error,

  • i just downloaded it but it doesn’t work! i’m working with NetBeans on Windows 8.

    The Exception
    Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'simpleDLL': Impossibile trovare il modulo specificato.

    at com.sun.jna.NativeLibrary.loadLibrary(
    at com.sun.jna.NativeLibrary.getInstance(
    at com.sun.jna.Library$Handler.(
    at com.sun.jna.Native.loadLibrary(
    at com.sun.jna.Native.loadLibrary(
    at mwrobel.jna.Main$simpleDLL.(
    at mwrobel.jna.Main.main(
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

    • sorry i’ve just read Alex’s post


  • […] Calling DLL functions from Java | Michał Wróbel’s blog – Short introduction and tutorial on Java Native Access (JNA) library. Invoking functions from DLL library. […]

  • Hi everyone,

    I want to interact with windows driver like wireless,volume control etc using java .please give me any solution I am beginners in netbeans 8.1 with JNA.but not get real time solutions

  • Hello, I’m using windows 7 32bits. I have the UnsatisfiedLinkError problem reported by so many here when using your dll michal. However I have been able to load the msvcrt.dll (most of you will have it in your System32 folder) and use the printf function, so I know my dlls are in the right place. I have tried loading other dlls and the problem I find is “UnsatisfiedLinkError: Error looking up function”. This error was already reported by Gigi.
    Does anyone have any clues how to solve this?

  • Indeed it is very informative and found it working.

  • Very usefull thank you

  • Hi,

    I am unable to download your code..wheni click on that link its redirectling to this page..please help me to download .dll and java code

    • both links from ‘Download’ section are working properly.

  • Hi Michal,
    I have used your method in my Project to load a dll library in Eclipse and it works properly.
    However, when I make a runnable .exe file from my Project, the ddl file does not load (without any error message) and program stops.
    Would you please guide me to solve this Problem.

  • After downloading and running the Java netbeans project, I found the following error,

    Exception in thread “main” java.lang.UnsatisfiedLinkError: Unable to load library ‘simpleDLL’: The specified module could not be found.

    at com.sun.jna.NativeLibrary.loadLibrary(
    at com.sun.jna.NativeLibrary.getInstance(
    at com.sun.jna.Library$Handler.(
    at com.sun.jna.Native.loadLibrary(
    at com.sun.jna.Native.loadLibrary(
    at mwrobel.jna.Main$simpleDLL.(
    at mwrobel.jna.Main.main(
    C:\Users\Enayet\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
    BUILD FAILED (total time: 0 seconds)

    where should I put the dll file?


  • Looks like the :

    java.lang.UnsatisfiedLinkError: Unable to load library ‘simpleDLL’

    is resolved via recompiling the dll with statically-linked components with the target platform similar to the one it’ll be running on. The “module could not be found” appears to be related to the dependencies rather than the library itself.
    This is for Windows platforms.

  • Also, for 64-bit systems the following line should read:

    //Memory intMem = new Memory(4); // allocating space
    Memory intMem = new Memory(8); // allocating space

    otherwise it crashes the JVM.

  • Hi,

    You have passed simpleDLL.class in method parameter but I need how to load simple.dll file .

    can anyone tell me how it possible.

  • if the dll method is defined in class,how can i reference its method in java?