首先是 JNA 需要的两个依赖包
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.2.0</version>
</dependency>
项目中 dll 文件存放位置
两种方式存放,选择任意一种都可以(推荐第一种)
项目 resources 目录下新建文件夹:win32-x86-64 ,并将 dll 文件放入其中
放入操作系统目录中 windows/system32/
JNA 的实现 demo
找到一个 dll 需要实现的接口(可以从对应的.h 文件中查找)
HANDLE __stdcall device_open(__int16 port,unsigned long baud);
在 JAVA 代码中调用接口(C/C++与 JAVA 类型对照表请往下看)
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.win32.StdCallLibrary;
public class JnaDemo {
public interface MTX32 extends StdCallLibrary {
/**
* 参数1:需要调用的dll文件名
*/
MTX32 INSTANCE = Native.load("mtx_32", MTX32.class);
/**
* 根据C与java参数对照表写出对应接口
*/
HANDLE device_open(Short port, NativeLong baud);
}
public static void main(String[] args) {
//调用接口
MTX32 mtx32 = MTX32.INSTANCE;
HANDLE handle = mtx32.device_open((short) 1, new NativeLong(115200, true));
System.out.println(handle);
}
}
Default Type Mappings
Java primitive types (and their object equivalents) map directly to the native C type of the same size.
Native Type | Size | Java Type | Common Windows Types |
---|---|---|---|
char | 8-bit integer | byte | BYTE, TCHAR |
short | 16-bit integer | short | WORD |
wchar_t | 16/32-bit character | char | TCHAR |
int | 32-bit integer | int | DWORD |
int | boolean value | boolean | BOOL |
long | 32/64-bit integer | NativeLong | LONG |
long long | 64-bit integer | long | __int64 |
float | 32-bit FP | float | |
double | 64-bit FP | double | |
char* | C string | String | LPTCSTR |
void* | pointer | Pointer | LPVOID, HANDLE, LPXXX |