Declaring external functions depending on whether they exist

I would like to declare an external function from the kernel32.dll library whose name is GetTickCount64. As far as I know, it is detected only in Vista and in later versions of Windows. This means that when I define a function as follows:

function GetTickCount64: int64; external kernel32 name 'GetTickCount64'; 

Of course, I will not be able to start the application in previous versions of Windows due to an error that occurred when starting the application.

Is there a workaround to this problem? Say I would like to not include this function when it does not exist, and then use some replacement function in my code. How to do it? Are there any compiler directives that will help? I believe that the definition should be surrounded by such a directive, and I will also need to use some directives, wherever I use the GetTickCount64 function, right?

Your help will be appreciated. Thanks in advance.

Mariusz.

+4
source share
1 answer

Declare a pointer to a function of this type, and then load the function at run time using LoadLibrary or GetModuleHandle and GetProcAddress . You can find some examples of this technique in the Delphi source code; look at TlHelp32.pas, which downloads the ToolHelp Library , which is not available on older versions of Windows NT.

 interface function GetTickCount64: Int64; implementation uses Windows, SysUtils; type // Don't forget stdcall for API functions. TGetTickCount64 = function: Int64; stdcall; var _GetTickCount64: TGetTickCount64; // Load the Vista function if available, and call it. // Raise EOSError if the function isn't available. function GetTickCount64: Int64; var kernel32: HModule; begin if not Assigned(_GetTickCount64) then begin // Kernel32 is always loaded already, so use GetModuleHandle // instead of LoadLibrary kernel32 := GetModuleHandle('kernel32'); if kernel32 = 0 then RaiseLastOSError; @_GetTickCount := GetProcAddress(kernel32, 'GetTickCount64'); if not Assigned(_GetTickCount64) then RaiseLastOSError; end; Result := _GetTickCount64; end; 
+11
source

All Articles