I'm having trouble getting my dll to work when using explicit linking. Using implicit linking it works fine. Would someone google me a solution? :) No, just kidding, here's my code:
This code works fine:
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 get an 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.
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;
See also http://www.drbob42.com/examines/examinC1.htm for a third solution, available in Delphi 2010, the Delayed loading of Dynamic Link Libraries...
procedure TForm1.Button1Click(Sender: TObject);
var
LibHandle: HMODULE;
CountChars: function(_s: PChar): integer;
In above line you have missed StdCall modifier.
精彩评论