隐式链接与Delphi中DLL的显式链接

时间:2010-04-20 08:29:06

标签: delphi dll

使用显式链接时,我无法使用dll工作。使用隐式链接可以正常工作。有人会给我一个解决方案吗? :)不,开个玩笑,这是我的代码:

此代码可以正常工作:

function CountChars(_s: Pchar): integer; StdCall; external 'sample_dll.dll';

procedure TForm1.Button1Click(Sender: TObject);
begin   
  ShowMessage(IntToStr(CountChars('Hello world')));
end;

此代码不起作用(我收到访问冲突):

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;

这是DLL代码:

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.

3 个答案:

答案 0 :(得分:7)

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;

答案 1 :(得分:3)

另请参阅http://www.drbob42.com/examines/examinC1.htm以获取Delphi 2010中提供的第三种解决方案,即动态链接库的延迟加载...

答案 2 :(得分:2)

procedure TForm1.Button1Click(Sender: TObject); 
var 
  LibHandle: HMODULE; 
  CountChars: function(_s: PChar): integer;

在上面一行中你错过了StdCall修饰符。