Java 使用 JNA 调 dll
1、准备jar
网上下载jar文件,这里使用的是jna-4.0.0.jar、jna-platform-4.0.0
2、创建dll
使用Visual Studio 2017创建dll(动态库)
#define __MAIN_H__ #include <windows.h> #ifdef BUILD_DLL #define DLL_EXPORT __declspec(dllexport) #else #define DLL_EXPORT __declspec(dllimport) #endif #ifdef __cplusplus extern "C" { #endif extern "C" __declspec(dllexport) int add(int a, int b); extern "C" __declspec(dllexport) int factorial(int n); extern "C" __declspec(dllexport) char* say(char* msg); extern "C" __declspec(dllexport) bool sayno(bool flag); #ifdef __cplusplus } #endif #endif // __MAIN_H_
// Dll3.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h" int add(int a, int b) { return a + b; } int factorial(int n) { int i; int r = 1; for (i = 1; i < n + 1; i++) r = r * i; return r; } char* say(char* msg) { return msg; } bool sayno(bool flag) { return !flag; } BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: // attach to process // return FALSE to fail DLL load break; case DLL_PROCESS_DETACH: // detach from process break; case DLL_THREAD_ATTACH: // attach to thread break; case DLL_THREAD_DETACH: // detach from thread break; } return TRUE; // succesful }
3、创建Java项目调用dll
package jna; import com.sun.jna.Library; import com.sun.jna.Native; public class Test { interface Dll3 extends Library { Dll3 INSTANCE = (Dll3) Native.loadLibrary("Dll3",Dll3.class); public int add(int a,int b); public int factorial(int n); public String say(String msg); public boolean sayno(boolean flag); } public static void main(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("测试返回结果:"+clib.add(13, 13)); System.out.println("测试返回结果:"+clib.factorial(1)); System.out.println("测试返回结果:"+clib.say("heoll wrold!!")); System.out.println("测试返回结果:"+clib.sayno(true)); } }
4、出现的问题
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function
导致这个问题出现的又很多原因基本上dll上引起的,检查函数名是否正确、检查参数是否正确、
extern "C" __declspec(dllexport)这个得加上要不然只是编译成功了dll,dll是不完整的。
这几个因素也可能导致失败!编译的dll和对应的jdk是64位还是32位。