【问题标题】:Implicit linking vs. explicit linking of DLL in DelphiDelphi中DLL的隐式链接与显式链接
【发布时间】:2010-04-20 08:29:05
【问题描述】:

使用显式链接时,我的 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.

【问题讨论】:

    标签: delphi dll


    【解决方案1】:
    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;
    

    【讨论】:

    • Tom,编译器没有警告过您没有在 Button1Click 中分配 CountChars 变量吗?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      procedure TForm1.Button1Click(Sender: TObject); 
      var 
        LibHandle: HMODULE; 
        CountChars: function(_s: PChar): integer;
      

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

      【讨论】:

      • 所有重要的 GetProcAddress 调用都不见了
      猜你喜欢
      • 2011-06-15
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多