如何从Delphi中生成的DLL导入函数?

你能告诉我如何在我的C程序中使用以下function吗?

Delphi 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:"); } 

谢谢

由于您没有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作为读者的练习:-)。

ShortString与PChar(char *)不同。 它是一个char数组,第一个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);