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);
}
}