JNA入门(一)
JNA入门,代码在github写得明明白白:https://github.com/java-native-access/jna/blob/master/www/GettingStarted.md
一、显示调用 kernel32.dll
首先知道kernel32.dll中获取系统时间的函数
// GetSystemTime(SYSTEMTIME result)
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;
Maven
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.10.0</version>
</dependency>
编写java接口,对应dll的接口
import com.sun.jna.Native;
import com.sun.jna.Structure;
import com.sun.jna.win32.StdCallLibrary;
/**
* @author lingkang
* @date 2021/12/20
*/
public interface Kernel32 extends StdCallLibrary {
Kernel32 INSTANCE = (Kernel32)
Native.load("kernel32", Kernel32.class);
@Structure.FieldOrder({"wYear", "wMonth", "wDayOfWeek", "wDay", "wHour", "wMinute", "wSecond", "wMilliseconds"})
public static class SYSTEMTIME extends Structure {
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
}
void GetSystemTime(SYSTEMTIME result);
}
编写调用的main方法
/**
* @author lingkang
* @date 2021/12/20
*/
public class Helloworld {
public static void main(String[] args) {
Kernel32 lib = Kernel32.INSTANCE;
Kernel32.SYSTEMTIME time = new Kernel32.SYSTEMTIME();
lib.GetSystemTime(time);
System.out.println(time.wYear+"-"+time.wMonth+"-"+time.wDay);
}
}
输出:
还有现成的依赖库:
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.10.0</version>
</dependency>
直接调用 Kernel32 .Dll
import com.sun.jna.platform.win32.Kernel32;
/**
* @author lingkang
* @date 2021/12/20
*/
public class Helloworld {
public static void main(String[] args) {
// Kernel32 lib = Kernel32.INSTANCE;
// Kernel32.SYSTEMTIME time = new Kernel32.SYSTEMTIME();
// lib.GetSystemTime(time);
//
// System.out.println(time.wYear+"-"+time.wMonth+"-"+time.wDay);
Kernel32 kernel32=Kernel32.INSTANCE;
Kernel32.SYSTEMTIME time = new Kernel32.SYSTEMTIME();
kernel32.GetSystemTime(time);
System.out.println(time.wYear+"-"+time.wMonth+"-"+time.wDay);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!