2009-04-25 31 views
4

我想從kernel32.dll庫中聲明一個名爲GetTickCount64的外部函數。據我所知,它僅在Vista和更高版本的Windows中定義。這意味着,當我定義的功能如下:根據它們是否存在聲明外部函數

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

我一定不能夠運行我的,因爲在應用程序啓動時產生的錯誤的以前版本的Windows應用程序。

是否有解決該問題的方法?假設我不想在不存在的時候包含這個函數,然後在我的代碼中使用一些替代函數。怎麼做?是否有任何編譯器指令可以幫助? 我覺得定義必須被這樣的指令所包圍,我也必須在使用GetTickCount64函數的地方使用一些指令,對吧?

您的幫助將不勝感激。提前致謝。

Mariusz。

回答

11

聲明該類型的函數指針,然後在運行時加載函數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; 
+0

感謝您的回答。我認爲這是我正在尋找的。 雖然我有一個問題。我想修改條件如下: 如果未指定(_GetTickCount64),則 @ _GetTickCount64:= @GetTickCount; 這是正確的嗎?正如你所看到的,當GetTickCount64沒有定義時,我使用了默認在「Windows」模塊中聲明的函數GetTickCount作爲替代。我明白我可以分配任何返回int64到_GetTickCount64變量的函數,對嗎?還是隻有一個外部功能?我還不知道stdcall關鍵字:-(。 – 2009-04-25 14:25:26

相關問題