微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

delphi – 根据它们是否存在来声明外部函数

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

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

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

这个问题有解决方法吗?假设我不想在不存在时包含该函数,然后在我的代码中使用一些替换函数.怎么做?是否有任何编译器指令可以帮助?
我猜这个定义必须被这样的指令所包围,我还必须使用一些指令,无论我在哪里使用GetTickCount64功能,对吧?

我们将不胜感激.提前致谢.

马里乌什.

解决方法

声明该类型的函数指针,然后在运行时使用 LoadLibraryGetModuleHandleGetProcAddress加载该函数.您可以在Delphi源代码中找到该技术的几个示例;看看TlHelp32.pas,它加载 ToolHelp library,这在旧版本的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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐