1. Prepare jar
Download the jar file online, using Jna-4.0.0.jar, jna-platform-4.0.0
2. Create DLL
Create a DLL using Visual Studio 2017 (Dynamic library)
#define__main_h__#include<windows.h>#ifdef Build_dll#defineDll_export __declspec (dllexport)#else#defineDll_export __declspec (dllimport)#endif#ifdef __cplusplusextern "C"{#endif extern "C"__declspec (dllexport)intAddintAintb); extern "C"__declspec (dllexport)intFactorial (intN); extern "C"__declspec (dllexport)Char* Say (Char*msg); extern "C"__declspec (dllexport)BOOLSayno (BOOLflag); #ifdef __cplusplus}#endif#endif //__main_h_
//Dll3.cpp: Defines an export function for a DLL application. //#include"stdafx.h"intAddintAintb) {returnA +b;}intFactorial (intN) {inti; intR =1; for(i =1; I < n +1; i++) R= R *i; returnR;}Char* Say (Char*msg) { returnmsg;}BOOLSayno (BOOLflag) { return!Flag;} BOOL WINAPI DllMain (hinstance hinstDLL, DWORD fdwreason, LPVOID lpvreserved) {Switch(Fdwreason) { CaseDll_process_attach://Attach to Process//return FALSE to fail DLL load Break; CaseDll_process_detach://Detach from Process Break; CaseDll_thread_attach://Attach to Thread Break; CaseDll_thread_detach://Detach from Thread Break; } returnTRUE;//succesful}
3. Create a Java Project call DLL
PackageJNA;Importcom.sun.jna.Library;Importcom.sun.jna.Native; Public classTest {InterfaceDll3extendsLibrary {Dll3 INSTANCE= (DLL3) native.loadlibrary ("Dll3", Dll3.class); Public intAddintAintb); Public intFactorial (intN); Publicstring Say (string msg); Public BooleanSayno (Booleanflag); } Public Static voidMain (string[] args) {//System.out.println (System.getproperty ("java.version"));//System.out.println (System.getproperty ("Sun.arch.data.model"));Dll3 Clib=dll3.instance; System.out.println ("Test results returned:" +clib.add (13, 13)); System.out.println ("Test results returned:" +clib.factorial (1)); System.out.println ("Test Returns the result:" +clib.say ("Heoll wrold!! ")); System.out.println ("Test results returned:" +clib.sayno (true)); }}
4. Problems that arise
Exception in thread ' main ' java.lang.UnsatisfiedLinkError:Error looking up function
There are many reasons for this problem, which is caused by the DLL, checking that the function name is correct, checking the parameters correctly,
extern "C" __declspec (dllexport) this plus or just compile successfully dll,dll is not complete.
These factors can also lead to failure! The compiled DLL and the corresponding JDK are 64-bit or 32-bit.
Java uses the JNA to tune DLLs