How to Check If Running in 64-bit Windows Environment using Delphi?

Posted on Posted in 64 bit, code, code library, delphi

The Win32 API IsWow64Process determines if a running process (Process Handler) is on WOW64, which is only set to TRUE, if the process is 32-bit and the OS is 64-bit.

On 64-bit Windows, 32-bit processes are running in the WOW64 (Windows 32-bit on Windows 64-bit) environment. Therefore, the IsWow64Process checks this situation.

The IsWow64Process API is defined in the windows DLL kernel32.dll, which can be loaded via LoadLibrary. However, you can load it once and cache the result for any successive calls. The following implements the IsWow64Process function in Delphi by calling the Win32 API IsWow64Process.

{$J+}
function IsWow64Process: Boolean;
type
  TIsWow64Process = function(hProcess: THandle; var Wow64Process: Boolean): Boolean; stdcall;
var
  DLL: THandle;
  pIsWow64Process: TIsWow64Process;
const
  Called: Boolean = False;
  IsWow64: Boolean = False;
begin
  if (Not Called) then // only check once
  begin
    DLL := LoadLibrary('kernel32.dll');
    if (DLL <> 0) then
    begin
      pIsWow64Process := GetProcAddress(DLLHandle, 'IsWow64Process');
      if (Assigned(pIsWow64Process)) then
      begin
        pIsWow64Process(GetCurrentProcess, IsWow64);
      end;
      Called := True; // avoid unnecessary loadlibrary
      FreeLibrary(DLLHandle);
    end;
  end;
  Result := IsWow64;
end;
{$J-}

To achieve this using Delphi, we use compiler directive {$J+} that allows the writable typed constants, which is similar to the static variables in C/C++. The Called and IsWow64 with {$J+} are writable typed constants, the scope of which are not terminated when function exits.