如何在Java中使用kernel32.dll
问题描述:
我想从Windows安装中获取一些信息。 我能够用C#下面的代码很容易地做到这一点,但我正在寻找一个Java实现。如何在Java中使用kernel32.dll
我需要访问下列变量和方法:
internal struct OSVERSIONINFOEX
{
public Int32 dwOSVersionInfoSize;
public Int32 dwMajorVersion;
public Int32 dwMinorVersion;
public Int32 dwBuildNumber;
public Int32 dwPlatFormId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public String szCSDVersion;
public short wServicePackMajor;
public short wServicePackMinor;
public short wSuiteMask;
public byte wProductType;
public byte wReserved;
}
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern Boolean GetVersionEx(ref OSVERSIONINFOEX osVersionInfo);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern Boolean GetProductInfo(
[In] Int32 dwOSMajorVersion,
[In] Int32 dwOSMinorVersion,
[In] Int32 dwSpMajorVersion,
[In] Int32 dwSpMinorVersion,
[Out] out Int32 pdwReturnedProductType);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern Boolean GetSystemMetrics([In] Int32 nIndex);
答
这里经过一些调查研究的是如何完成任务。你必须使用JNA库。
public interface Kernel32 extends com.sun.jna.platform.win32.Kernel32 {
// Method declarations, constant and structure definitions go here
Kernel32 INSTANCE = (Kernel32)
Native.loadLibrary("kernel32", Kernel32.class, com.sun.jna.win32.W32APIOptions.DEFAULT_OPTIONS);
boolean GetVersionEx(WinNT.OSVERSIONINFOEX osVersionInfo);
boolean GetProductInfo(
int dwOSMajorVersion,
int dwOSMinorVersion,
int dwSpMajorVersion,
int dwSpMinorVersion,
IntByReference pdwReturnedProductType);
boolean GetSystemMetrics(int nIndex);
}
public static boolean GetVersionInfo(WinNT.OSVERSIONINFOEX osVersionInfo) {
return Kernel32.INSTANCE.GetVersionEx(osVersionInfo);
}
要获得信息,你再运行在你的代码如下:
WinNT.OSVERSIONINFOEX osVersionInfo = new WinNT.OSVERSIONINFOEX();
if (!NativeMethods.GetVersionInfo(osVersionInfo)) {
System.out.println("Info failed to load!");
}
您需要的[JNI]一个(http://docs.oracle.com/javase/8/docs/technotes/guides/jni /)*或* [JNA](https://github.com/java-native-access/jna)。 –
谢谢,我明白了。我很快会回答我自己的问题。 –