写在前面:最近碰到个项目,客户是搞C语言的,需求要在项目中开放接口调用现成的dll文件
然后去了解了下Java中调用dll的几种方式,总的有三种:JNI、JNA、JNative。其中JNA调用DLL是最方便的。
注意:要调用的DLL位数要与JDK位数相同,若dll为32位则jdk也要32位的,若dll为64位的,则jdk为64位的,否则无法调用。
·JNI
·JNA
·JNative
java使用 JNI来调用dll动态库的调用,工作量略大,一般情况下开发人员会选用JNA或JNative。
使用JNative调用DLL除了要引入jar包外还需要额外引入一个dll文件,而JNA只需要引入jar即可使用。
代码示例
本代码示例基于 64位 win10
添加需要的依赖
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.3.1</version>
</dependency>
// c++ 需要在 vs 中编译成 dll
int AddXY(int x, int y) {
return x+y;
}
Java代码
public interface CLibrary extends Library {
// DLL文件默认路径为项目根目录,若DLL文件存放在项目外,请使用绝对路径
// CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
// CLibrary.class);
// 下面目录是我本地测试文件路径
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("C:\\Users\\zl\\Desktop\\Dll2_x64", CLibrary.class);
// 声明将要调用的DLL中的方法(可以是多个方法)
int AddXY(int x, int y);
}
public static void main(String[] args) {
int xy = CLibrary.INSTANCE.AddXY(2, 3);
System.out.println(xy);
}
运行结果:
完整代码如下:
package com.redis.lock.demo.dll;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.win32.StdCallLibrary;
/**
* JNA框架DLL动态库读取调用示例类
*
* @ClassName: DllCall
* @Description: 读取调用DLL动态库文件中的方法
* @author: zl
* @date: 2020年05月26日 下午11:08:16
*/
public class JNADllCall {
/**
* DLL动态库调用方法1
*
* @Description: 读取调用StdCall方式导出的DLL动态库方法
* @author: zl
* @date: 2020年05月26日 下午11:08:16
*/
public interface StdCallDll extends StdCallLibrary {
// DLL文件默认路径为项目根目录,若DLL文件存放在项目外,请使用绝对路径
StdCallDll INSTANCE = (StdCallDll) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
StdCallDll.class);// 加载动态库文件
// 声明将要调用的DLL中的方法(可以是多个方法)
void printf(String format, Object... args);
}
/**
* DLL动态库调用方法2
*
* @Description: 读取调用Decl方式导出的DLL动态库方法
* @author: zl
* @date: 2020年05月26日 下午11:08:16
*/
public interface CLibrary extends Library {
// DLL文件默认路径为项目根目录,若DLL文件存放在项目外,请使用绝对路径
// CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
// CLibrary.class);
// 下面目录是我本地测试文件路径
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("C:\\Users\\zl\\Desktop\\Dll2_x64", CLibrary.class);
// 声明将要调用的DLL中的方法(可以是多个方法)
int AddXY(int x, int y);
}
public static void main(String[] args) {
int xy = CLibrary.INSTANCE.AddXY(2, 3);
System.out.println(xy);
}
}
以上简单记录java通过JNA框架调用DLL动态库的步骤,若需要进一步了解可参考以下博文地址:https://www.jianshu.com/p/ead89497c403