Implicit binding to an explicit DLL reference in Delphi
I am having trouble getting my dll to work when using an explicit reference. Using an implicit reference works great. Can anyone tell me a solution? :) No, just kidding, here's my code:
This code works great:
function CountChars(_s: Pchar): integer; StdCall; external 'sample_dll.dll';
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(CountChars('Hello world')));
end;
This code doesn't work (I'm getting access violation):
procedure TForm1.Button1Click(Sender: TObject);
var
LibHandle: HMODULE;
CountChars: function(_s: PChar): integer;
begin
LibHandle := LoadLibrary('sample_dll.dll');
ShowMessage(IntToStr(CountChars('Hello world'))); // Access violation
FreeLibrary(LibHandle);
end;
This is the DLL code:
library sample_dll;
uses
FastMM4, FastMM4Messages, SysUtils, Classes;
{$R *.res}
function CountChars(_s: PChar): integer; stdcall;
begin
Result := Length(_s);
end;
exports
CountChars;
begin
end.
+2
a source to share
3 answers
procedure TForm1.Button1Click(Sender: TObject);
var
LibHandle: HMODULE;
CountChars: function(_s: PChar): integer; stdcall; // don't forget the calling convention
begin
LibHandle := LoadLibrary('sample_dll.dll');
if LibHandle = 0 then
RaiseLastOSError;
try
CountChars := GetProcAddress(LibHandle, 'CountChars'); // get the exported function address
if not Assigned(@CountChars) then
RaiseLastOSError;
ShowMessage(IntToStr(CountChars('Hello world')));
finally
FreeLibrary(LibHandle);
end;
end;
+7
a source to share
See also http://www.drbob42.com/examines/examinC1.htm for a third solution available in Delphi 2010, Delay loading dynamic link libraries ...
+3
a source to share