2010-04-20 62 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