我想分享我的 Java 代码解决方案(类似的是本机代码)。
我想补充一下 James Van Huis 先生的回答;由于属性 os.arch System.getProperty("os.arch") 返回 JRE 的位数,这实际上非常有用。来自文章:
在您的代码中,您首先需要检查 IntPtr 的大小,如果它返回 8,那么您运行的是 64 位操作系统。如果它返回 4,那么你正在运行一个 32 位应用程序,所以现在你需要知道你是在本机运行还是在 WOW64 下运行。
因此,IntPtr 大小检查与您通过查看“os.arch”执行的检查相同。在此之后,您可以继续确定该进程是在本机运行还是在 WOW64 下运行。
这可以使用 jna 库(例如NativeLibrary)来完成,它提供了您需要的本地函数的使用。
//test the JRE here by checking the os.arch property
//go into the try block if JRE is 32bit
try {
NativeLibrary kernel32Library = NativeLibrary.getInstance("kernel32");
Function isWow64Function = kernel32Library.getFunction("IsWow64Process");
WinNT.HANDLE hProcess = Kernel32.INSTANCE.GetCurrentProcess();
IntByReference isWow64 = new IntByReference(0);
Boolean returnType = false;
Object[] inArgs = {
hProcess,
isWow64
};
if ((Boolean) isWow64Function.invoke(returnType.getClass(), inArgs)) {
if (isWow64.getValue() == 1) {
//32bit JRE on x64OS
}
}
} catch (UnsatisfiedLinkError e) { //thrown by getFunction
}
类似的方法也可能有效,但我会推荐第一个版本,因为它是我在 x64 操作系统上的 x64 和 32 位 JRE 上测试的版本。它也应该是更安全的方法,因为在下面你实际上并没有检查“IsWow64Process”函数是否存在。
这里我添加了一个 JRE 检查的示例,以确保它是完整的,尽管它并不难找到。
Map<String, Integer> archMap = new HashMap<String, Integer>();
archMap.put("x86", 32);
archMap.put("i386", 32);
archMap.put("i486", 32);
archMap.put("i586", 32);
archMap.put("i686", 32);
archMap.put("x86_64", 64);
archMap.put("amd64", 64);
//archMap.put("powerpc", 3);
this.arch = archMap.get(SystemUtils.OS_ARCH);
if (this.arch == null) {
throw new IllegalArgumentException("Unknown architecture " + SystemUtils.OS_ARCH);
}