Java使用JNA调用DLL文件
作者:汪小成
JNA(Java Native Access)是一个在 Java 中调用本地代码的开源框架,提供了一种简单、高效的方式来访问本地动态链接库,下面我们来看看Java如何使用JNA调用DLL文件吧
1、什么是JNA?
JNA(Java Native Access)是一个在 Java 中调用本地代码的开源框架,提供了一种简单、高效的方式来访问本地动态链接库(如 .dll、.so 文件)。
2、JNA的使用步骤
1、引入依赖
在pom.xml文件中添加如下内容:
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.15.0</version>
</dependency>
2、定义接口
精伦读卡器官网提供了一个32位的Sdtapi.dll文件。先在接口文件中加载此DLL文件,然后在接口文件中定义需要调用的方法。
接口需要继承com.sun.jna.Library。本地接口的详细代码如下:
import com.sun.jna.Library;
import com.sun.jna.Native;
/**
* 精伦身份证阅读器
*/
public interface JLLibrary extends Library {
JLLibrary INSTANCE = Native.load("D:\\23-demo\\Sdtapi", JLLibrary.class);
/**
* 打开串口
* @param port 端口号
* @return 1 - 正确;其它 - 失败
*/
int InitComm(int port);
/**
* 卡认证
* @return 1 - 正确;其它 - 失败
*/
int Authenticate();
/**
* 读取卡信息
* @param name 姓名
* @param gender 性别
* @param nation 民族
* @param birthday 出生日期,格式:yyyyMMdd
* @param code 身份证号码
* @param address 地址
* @param agency 签证机关信息
* @param beginDate 有效期(起始日期)
* @param endDate 有效期(结束日期)
* @return 1 - 正确;其它 - 失败
*/
int ReadBaseInfos(byte[] name, byte[] gender, byte[] nation, byte[] birthday, byte[] code, byte[] address,
byte[] agency, byte[] beginDate, byte[] endDate);
/**
* 关闭串口
* @return 1 - 正确;其它 - 失败
*/
int CloseComm();
}
方法名、参数及返回结果同精伦官方提供的对接文档中的完全一致。
3、调用接口方法
精伦读取器读取身份证信息的流程:
1.打开串口 2.卡认证 3.读取身份证信息 4.关闭串口
接下来要做的就是按照上面的步骤调用接口方法。调用接口方法的部分代码如下:
// 1.打开串口,具体端口数值参考官方对接文档
int deviceResult = JLLibrary.INSTANCE.InitComm(1001);
if (deviceResult == 1) {
// 2.卡认证
JLLibrary.INSTANCE.Authenticate();
byte[] name = new byte[31];
byte[] gender = new byte[3];
byte[] nation = new byte[10];
byte[] birthday = new byte[9];
byte[] code = new byte[19];
byte[] address = new byte[71];
byte[] agency = new byte[31];
byte[] beginDate = new byte[9];
byte[] endDate = new byte[9];
// 3.读取基本信息
int readResult = JLLibrary.INSTANCE.ReadBaseInfos(name, gender, nation, birthday, code, address, agency, beginDate, endDate);
// 解析
System.out.println(new String(name, "GBK"));
System.out.println(new String(gender, "GBK"));
System.out.println(new String(nation, "GBK"));
System.out.println(new String(birthday, "GBK"));
System.out.println(new String(code, "GBK"));
System.out.println(new String(address, "GBK"));
System.out.println(new String(agency, "GBK"));
System.out.println(new String(beginDate, "GBK"));
System.out.println(new String(endDate, "GBK"));
// 4.关闭串口
deviceResult = JLLibrary.INSTANCE.CloseComm();
if (deviceResult == 1) {
System.out.println("身份证阅读器关闭成功。");
} else {
System.out.println("身份证阅读器关闭失败!");
}
} else {
System.out.println("身份证阅读器打开失败!");
}
4、运行程序
运行程序这一步本身是没有必要讲述的,只是作者汪小成开发用的电脑是WIN10 64位系统,不能调用32位的DLL文件,所以程序不能直接使用IDEA中运行。作者汪小成这里采用的方式是在将程序打成JAR,接着在开发电脑上安装一个32位的JDK,最后使用32位的JDK运行打包后的JAR文件。
到此这篇关于Java使用JNA调用DLL文件的文章就介绍到这了,更多相关Java JNA调用DLL文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
