[英]How to detect if Windows supports running x64 processes?
从 2020 年 12 月开始, Windows 支持 ARM64 设备上的 x64 仿真。 程序如何确定当前版本的 Windows 是否支持运行 x64 应用程序?
在 ARM64 上进行 x64 仿真之前,我们可以为此使用RuntimeInformation.OSArchitecture == Architecture.X64
。
您可以使用GetMachineTypeAttributes
( https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getmachinetypeattributes ) 检查 Windows 是否支持运行 x64 代码。
例如:
using System;
using System.Runtime.InteropServices;
public class Program
{
[Flags]
enum MachineAttributes
{
None = 0,
UserEnabled = 0x00000001,
KernelEnabled = 0x00000002,
Wow64Container = 0x00000004,
}
[DllImport("kernel32.dll", PreserveSig = false)]
static extern MachineAttributes GetMachineTypeAttributes(ushort WowGuestMachine);
const ushort IMAGE_FILE_MACHINE_AMD64 = 0x8664;
const ushort IMAGE_FILE_MACHINE_I386 = 0x014c;
const ushort IMAGE_FILE_MACHINE_ARM64 = 0xAA64;
public static void Main()
{
var x64Support = GetMachineTypeAttributes(IMAGE_FILE_MACHINE_AMD64);
Console.WriteLine("x64 support: {0}", x64Support);
var x86Support = GetMachineTypeAttributes(IMAGE_FILE_MACHINE_I386);
Console.WriteLine("x86 support: {0}", x86Support);
var arm64Support = GetMachineTypeAttributes(IMAGE_FILE_MACHINE_ARM64);
Console.WriteLine("Arm64 support: {0}", arm64Support);
}
}
在 x64 设备上运行它会产生:
x64 support: UserEnabled, KernelEnabled
x86 support: UserEnabled, Wow64Container
Arm64 support: None
在 Arm64 Win11 设备上产生:
x64 support: UserEnabled
x86 support: UserEnabled, Wow64Container
Arm64 support: UserEnabled, KernelEnabled
因此,要检测 x64 代码是否可以运行,请检查返回值是否不是MachineAttributes.None
:
public static bool SupportsX64()
{
return GetMachineTypeAttributes(IMAGE_FILE_MACHINE_AMD64) != MachineAttributes.None;
}
更新
看起来GetMachineTypeAttributes
是在 Win11 中添加的,因此如果尝试 P/Invoke 它会抛出EntryPointNotFoundException
,那么您就知道您在 Win11 之前运行并且可以使用旧的检测逻辑:
public static bool SupportsX64()
{
try
{
// Win11+: Ask the OS if we can run AMD64 code.
return GetMachineTypeAttributes(IMAGE_FILE_MACHINE_AMD64) != MachineAttributes.None;
}
catch (EntryPointNotFoundException)
{
// Pre-Win11: Only x64 machines can run x64 code.
return RuntimeInformation.OSArchitecture == Architecture.X64;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.