Domanda

Puoi dirmi come posso usare le seguenti funzioni nel mio programma C.

Delphi DLL - Funzioni esportate:

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

Non ho il codice sorgente per quella DLL, quindi devo adattare il mio programma C a quella DLL e non viceversa.

Faccio quanto segue e ricevo l'errore

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

Grazie

È stato utile?

Soluzione

Dal momento che non hai l'origine della DLL, dovrai creare un po 'di creatività sul lato C. Anche se ShortString è elencato come risultato della funzione, in realtà è responsabilità del chiamante fornire una posizione in cui posizionare il risultato. Poiché si tratta di una funzione stdcall, i parametri vengono passati da destra a sinistra, quindi significa che l'indirizzo del risultato ShortString viene passato per ultimo. Per ottenere questo allineamento, sarà necessario il primo parametro elencato. Farò la prima API, GetCPUID. In C, potrebbe assomigliare a questo:

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
}

Lascio GetPartitionID come esercizio per il lettore :-).

Altri suggerimenti

ShortString non è lo stesso di PChar (char *). È un array di caratteri con il primo carattere che è la lunghezza della stringa. Per C è meglio usare PChar (char *) fino in fondo.

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top