4

我想从名为 GetTickCount64 的 kernel32.dll 库中声明一个外部函数。据我所知,它仅在 Vista 和更高版本的 Windows 中定义。这意味着当我如下定义函数时:

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

由于应用程序启动时产生的错误,我肯定无法在以前版本的 Windows 上运行我的应用程序。

有解决该问题的方法吗?假设我不想在它不存在时包含该函数,然后在我的代码中使用一些替代函数。怎么做?是否有任何编译器指令会有所帮助?我猜定义必须被这样的指令包围,而且我还必须在使用 GetTickCount64 函数的任何地方使用一些指令,对吧?

您的帮助将不胜感激。提前致谢。

马吕斯。

4

1 回答 1

12

声明该类型的函数指针,然后在运行时使用LoadLibraryorGetModuleHandle和加载该函数GetProcAddress。您可以在 Delphi 源代码中找到该技术的几个示例;查看TlHelp32.pas,它加载ToolHelp 库,旧版本的 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;
于 2009-04-25T13:51:58.540 回答