2010-04-20 6 views
2

J'ai des difficultés à faire fonctionner ma DLL lors de l'utilisation de la liaison explicite. En utilisant la liaison implicite, cela fonctionne bien. Est-ce que quelqu'un me chercherait une solution? :) Non, je plaisante, voici mon code:Liaison implicite ou liaison explicite de DLL dans Delphi

Ce code fonctionne très bien:

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

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

Ce code ne fonctionne pas (je reçois une violation d'accès):

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; 

C'est le code de 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. 

Répondre

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

Merci! Cela a résolu le problème. GetProcAddress manquait – Tom

+1

Tom, le compilateur ne vous a-t-il pas averti que la variable 'CountChars' n'était pas affectée dans Button1Click? –

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

en lin ci-dessus e vous avez manqué le modificateur StdCall.

+0

Et tout appel important à GetProcAddress manque –

Questions connexes