Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
973 views
in Technique[技术] by (71.8m points)

delphi - Putting classes in a DLL?

Is it possible to put some classes into a DLL?

I have several custom classes in a project I am working on and would like to have them put in a DLL and then accessed in the main application when needed, plus if they are in a DLL I can reuse these classes in other projects if I need to.

I found this link: http://www.delphipages.com/forum/showthread.php?t=84394 which discusses accessing classes in a DLL and it mentions delegating to a class-type property but I could not find any further information on this in the Delphi help or online.

Is there any reason I should not put classes in a DLL, and if it is ok is there a better way of doing it then in the example from the link above?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...