2010-04-20 64 views
2

我在使用显式链接时无法让我的dll工作。使用隐式链接它工作正常。有人会告诉我一个解决方案吗? :)不,只是开个玩笑,这是我的代码:Delphi中的隐式链接与显式链接的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. 

回答

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; 
+0

谢谢!这解决了这个问题。 GetProcAddress丢失 – Tom 2010-04-20 09:41:18

+1

Tom,没有编译器警告你'CountChars'变量没有在Button1Click中赋值? – 2010-04-20 15:33:03

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

在上述林e您错过了StdCall修改器。

+0

而给GetProcAddress所有重要的电话丢失 – 2010-04-20 09:02:00