1. 程式人生 > >如何檢測當前作業系統是64位還是32位

如何檢測當前作業系統是64位還是32位

目前有幾種方法:

一,採用MSDN推薦的一個方法,通過呼叫kernel.dll中的IsWow64Process來判斷系統是否是64位的OS。

MSDN中給了一段程式碼:

BOOL IsWow64()
{
    typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
    LPFN_ISWOW64PROCESS fnIsWow64Process;
    BOOL bIsWow64 = FALSE;
    fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress( GetModuleHandle

(_T("kernel32")), "IsWow64Process");
    if (NULL != fnIsWow64Process)
    {
        fnIsWow64Process(GetCurrentProcess(),&bIsWow64);
    }
    return bIsWow64;
}

不過這個方法之適用於Win32_based application運行於WOW的情況(WOW的含義可查詢MSDN)。如果Win64_based application 運行於64位作業系統上,bIsWow64的返回值將會是FALSE。因此MSDN中有如下一段話:

To determine whether a Win32-based application is running on WOW64, call the

IsWow64Process function. To determine whether the system is running a 64-bit version of Windows, call the GetNativeSystemInfo function.

另外,如果你用Visual Studio進行編譯,預設安裝則只包含32位的編譯器/連結器,即便你是在64位作業系統上也會生成32位程式。

同時,在64位的作業系統上執行的kernel32.dll中,將會實現IsWow64Process方法,而在32位系統中提供的kernel32.dll中則沒有提供相關函式的實現。因此上面程式碼需要加以改進才能正常執行。

BOOL IsWow64(void)
{
 UINT   unResult   =   0;
 int   nResult   =   0;
 TCHAR   szWinSysDir[MAX_PATH+1]   =   _T("");
 TCHAR szKernel32File[MAX_PATH+1+14]   =  _T("");
 HINSTANCE   hLibKernel32   =   NULL;
 BOOL   bIsWow64Process   =   FALSE;

   
 typedef BOOL (WINAPI *ISWOW64)(HANDLE,PBOOL);
 ISWOW64 lpIsWow64Process = NULL;

 unResult   =   GetSystemDirectory(szWinSysDir,sizeof(szWinSysDir)/sizeof(TCHAR));
 if(unResult   >   0){
  nResult   =   _stprintf(szKernel32File,_T( "%s//kernel32.dll "),szWinSysDir);
  if(nResult   >   0){
   hLibKernel32   =   LoadLibrary(szKernel32File);
  }
 }

 if(NULL   ==   hLibKernel32){
  hLibKernel32   =   LoadLibrary(_T( "kernel32.dll "));
 }

 //   Get   the   Address   of   Win32   API   --   IsWow64Process()
 if(   NULL   !=   hLibKernel32   ){
  lpIsWow64Process  =  (ISWOW64) GetProcAddress(hLibKernel32,"IsWow64Process");
 }

 if(NULL   !=   lpIsWow64Process){
  //   Check   whether   the   32-bit   program   is   running   under   WOW64   environment.
  if(!lpIsWow64Process(GetCurrentProcess(),&bIsWow64Process)){
   FreeLibrary(hLibKernel32);
   return   FALSE;
  }
 }
 if(NULL   !=   hLibKernel32){
  FreeLibrary(hLibKernel32);
 }

 return  bIsWow64Process;
}

二,正如上面提到的MSDN中的說明,如果需要獲取更多詳細的資訊,推薦呼叫GetNativeSystemInfo