tags:

views:

216

answers:

3

I'm having trouble getting my dll to work when using explicit linking. Using implicit linking it works fine. Would someone google me a solution? :) No, just kidding, here's my code:

This code works fine:

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

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

This code doesn't work (I get an access violation):

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;

This is the DLL code:

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.
+2  A: 
procedure TForm1.Button1Click(Sender: TObject); 
var 
  LibHandle: HMODULE; 
  CountChars: function(_s: PChar): integer;

In above line you have missed StdCall modifier.

da-soft
And the all important call to GetProcAddress is missing
Lars Truijens
+7  A: 
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;
TOndrej
Thanks! This solved the problem. GetProcAddress was missing
Tom
Tom, didn't the compiler warn you that the `CountChars` variable wasn't assigned in Button1Click?
Rob Kennedy
+3  A: 

See also http://www.drbob42.com/examines/examinC1.htm for a third solution, available in Delphi 2010, the Delayed loading of Dynamic Link Libraries...

Bob Swart