add these web sites

怎样判断所运行的是X64系统

Posted by micki on August 02, 2018, sorted in Windows Application Development

怎样判断所运行的是X64系统

很多时候我们的程序需要判断自己的程序是运行于x86 32位系统还是运行于x64 64位系统, 其实仔细想想该问题只会发生在32bit的程序里, 因为编译为x64的可执行文件是无法运行于x86系统的, 而x64的系统可以以WOW64方式运行32位应用程序, 因此如果我们编译为x64的程序且能运行, 那么运行该程序的宿主系统必然是64位的, 也因此我们只需要在编译为32位程序时做判断即可.
 
那么如何写一段代码可同时运行于32位和64位程序里判断宿主系统是x86还是x64呢?
首先, 可以根据sizeof(LONG_PRT)的位数判断自己是32位还是64位的, 如果sizeof(LONG_PRT) == 8那么自己是64位的, 程序能跑, 操作系统也必然是64位的.
 
如果sizeof(LONG_PRT) == 4, 那么程序是32位的, 这时就可以根据IsWow64Process来判断自己是以WOW64方式来运行, 下一段是MSDN上关于IsWow64Process的原话:
 
For compatibility with operating systems that do not support this function, call GetProcAddress to detect whether IsWow64Message is implemented in User32.dll. If GetProcAddress succeeds, it is safe to call this function. Otherwise, WOW64 is not present. Note that this technique is not a reliable way to detect whether the operating system is a 64-bit version of Windows because the User32.dll in current versions of 32-bit Windows also contains this function.
 
综上所述我们可以写一个通用于x86和x64的函数来判断自己的程序是否运行于x64系统:
BOOL IsWindowsX64()
{
BOOL bX64 = FALSE;
BOOL bIsWow64 = FALSE;
LPFN_ISWOW64PROCESS fnIsWow64Process = NULL;
 
if(sizeof(LONG_PTR) >= 8)
{ // this is a x64 program
bX64 = TRUE;
}
else
{ // this is a x86 program
fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(_T("kernel32")), "IsWow64Process");
if(fnIsWow64Process)
{
fnIsWow64Process(GetCurrentProcess(), &bIsWow64);
if(bIsWow64)
{
bX64 = TRUE;
}
}
}
 
return bX64;
}
 

Recent Posts