Putting classes in a DLL?

It is not possible to get a Class/Instance from a DLL.
Instead of the class you can hand over an interface to the class.
Below you find a simple example

// The Interface-Deklaration for Main and DLL
unit StringFunctions_IntfU;

interface

type
  IStringFunctions = interface
    ['{240B567B-E619-48E4-8CDA-F6A722F44A71}']
    function CopyStr( const AStr : WideString; Index, Count : Integer ) : WideString;
  end;

implementation

end.

The simple DLL

library StringFunctions;

uses
  StringFunctions_IntfU; // use Interface-Deklaration

{$R *.res}

type
  TStringFunctions = class( TInterfacedObject, IStringFunctions )
  protected
    function CopyStr( const AStr : WideString; Index : Integer; Count : Integer ) : WideString;
  end;

  { TStringFunctions }

function TStringFunctions.CopyStr( const AStr : WideString; Index, Count : Integer ) : WideString;
begin
  Result := Copy( AStr, Index, Count );
end;

function GetStringFunctions : IStringFunctions; stdcall; export;
begin
  Result := TStringFunctions.Create;
end;

exports
  GetStringFunctions;

begin
end.

And now the simple Main Program

uses
  StringFunctions_IntfU;  // use Interface-Deklaration

// Static link to external function
function GetStringFunctions : IStringFunctions; stdcall; external 'StringFunctions.dll' name 'GetStringFunctions';

procedure TMainView.Button1Click( Sender : TObject );
begin
  Label1.Caption := GetStringFunctions.CopyStr( Edit1.Text, 1, 5 );
end;

Leave a Comment