简体   繁体   中英

I'm getting an access violation when using the LoadLibrary and GetProcAddress in Delphi

I'm getting access violation when trying call a simple dll using LoadLibrary:

Access violation at address 03454D62 in module 'test_dll.dll'. Write of address 00429D24.

Code for Test.DLL:

library Test_DLL;

uses
  dialogs;

{$R *.res}


procedure Test(source, dest : string);stdcall;
begin
  messageDlg('Source: ' + source + chr(13) + 'Dest: ' + dest, mtInformation, [mbOk], 0);
end;

Exports
  Test;

begin
end.

Calling the function using this:

procedure TForm6.Button1Click(Sender: TObject);
type
  TCheckMessage = procedure (test1, test2 : string);
var
  CheckMessage : TCheckMessage;
  DLLHandle : Cardinal;

const
  DLL_FILE = 'test_dll.dll';
  DLL_PROC = 'Test';
begin
  dllHandle := LoadLibrary(DLL_FILE) ;
   if dllHandle <> 0 then
   begin
     @CheckMessage := GetProcAddress(dllHandle, DLL_PROC) ;
     if Assigned (CheckMessage) then
       CheckMessage('test1', 'test2')  //call the function
     else
       ShowMessage('"' + DLL_PROC + '" function not found') ;
     FreeLibrary(dllHandle) ;
   end
   else
     ShowMessage(DLL_FILE + ' not found / not loaded') ;
end;

This seems like an easy thing to do, but I must be missing something. I did notice that the DLL procedure calls seem to be case-sensitive. It does appear the that procedure call is happening. DLLHandle and @CheckMessage are getting populated and the code runs, but throws an access violation as soon as:

CheckMessage('test1', 'test2')

is called.

You are not allowed to pass string across a DLL boundary. You might get away with it if you use a shared memory manager (as described in the comment that you deleted from the top of the library unit). And if you use the exact same version of Delphi to compile both DLL and executable.

Instead you should use interop safe types. For instance PAnsiChar , PWideChar or WideString .

Your other problem is a mismatch of signatures. The exported function uses stdcall calling convention. But when you import it, you use the default register calling convention. Clearly the calling convention needs to match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM