2009-03-04 66 views
1

你能告訴我如何在我的C程序中使用以下功能。如何從德爾福的DLL中導入函數?

德爾福DLL - 導出功能:

function GetCPUID (CpuCore: byte): ShortString; stdcall; 
function GetPartitionID(Partition : PChar): ShortString; stdcall; 

我沒有爲DLL的源代碼,所以我必須適應我的C程序到DLL,而不是周圍的其他方式。

我做以下,並得到錯誤

typedef char* (_stdcall *GETCPUID)(BYTE); 
typedef char* (_stdcall *GETPID)(PCHAR); 
GETCPUID pGetSerial; 
GETPID pGetPID 

HMODULE hWtsLib = LoadLibrary("HardwareIDExtractor.dll"); 
if (hWtsLib){ 
pGetSerial = (GETCPUID)GetProcAddress(hWtsLib, "GetCPUID"); 
char *str = (char*) malloc(1024); 
str = pGetSerial((BYTE)"1"); 

pGetPID= (GETPID)GetProcAddress(hWtsLib, "GetPartitionID"); 
char *str1 = (char*) malloc(1024); 
str1 = pGetPID("C:"); 
} 

感謝

+0

你準確得到了什麼錯誤?沒有這些信息就很難提供幫助。 – rusvdw 2009-03-04 14:49:08

+0

該程序編譯並運行,但在調用DLL函數時崩潰。 – Ampere 2009-03-05 09:04:28

回答

7

由於您沒有DLL的源代碼,因此您需要在C方面獲得一點創意。即使ShortString被列爲功能結果,它實際上是調用者提供放置結果的位置的責任。因爲這是一個stdcall函數,參數從右向左傳遞,所以這意味着ShortString結果的地址最後傳入。爲了排列起來,它需要列出第一個參數。我會做第一個API,GetCPUID。在C語言中,它可能是這個樣子:

typedef struct ShortString { 
    char len; 
    char data[255]; 
}; 
typedef void (_stdcall *GETCPUID)(struct ShortString *result, BYTE cpuCore); 

GETCPUID pGetSerial; 

HMODULE hWtsLib = LoadLibrary("HardwareIDExtractor.dll"); 
if (hWtsLib) { 
    ShortString serial; 
    pGetSerial = (GETCPUID)GetProcAddress(hWtsLib, "GetCPUID"); 
    pGetSerial(&serial, '1'); 
    char *str = malloc(serial.len + 1); // include space for the trailing \0 
    strlcpy(str, serial.data, serial.len); 
    str[serial.len] = '\0'; // drop in the trailing null 
} 

我將離開GetPartitionID作爲練習讀者:-)。

1

ShortString短是不一樣的PChar類型(字符*)。它是一個char數組,第一個字符是字符串的長度。對於C來說,最好是一路使用PChar(char *)。

procedure GetCPUID (CpuCore: byte; CpuId: PChar; Len: Integer); stdcall; 
procedure GetPartitionID(Partition : PChar; PartitionId: PChar; Len: Integer); stdcall; 

typedef (_stdcall *GETCPUID)(BYTE, char*, int); 
typedef (_stdcall *GETPID)(PCHAR, char*, int); 
GETCPUID pGetSerial; 
GETPID pGetPID 

HMODULE hWtsLib = LoadLibrary("HardwareIDExtractor.dll"); 
if (hWtsLib){ 
pGetSerial = (GETCPUID)GetProcAddress(hWtsLib, "GetCPUID"); 
char *str = (char*) malloc(1024); 
pGetSerial((BYTE)"1", str, 1024); 

pGetPID= (GETPID)GetProcAddress(hWtsLib, "GetPartitionID"); 
char *str1 = (char*) malloc(1024); 
pGetPID("C:", str, 1024); 
+0

我沒有該DLL的源代碼,所以我可以將我的C程序調整到該DLL,而不是其他方式。 – Ampere 2009-03-04 15:47:51