Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a Interface to a Object in Delphi

In delphi 2009 I have a reference to a IInterface which I want to cast to the underlying TObject

Using TObject(IInterface) obviously doesn't work in Delphi 2009 (it's supposed to work in Delphi 2010 though)

My searches lead me to a function that should do the trick, but it doesn't work for me, I get AV's when I try to call methods on the returned object.

I can't really modify the Classes and I know that this breaks OOP

like image 584
Yona Avatar asked Nov 09 '10 20:11

Yona


People also ask

Can you cast an interface to an object?

Yes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.

What is casting to an interface?

You can access the members of an interface through an object of any class that implements the interface. For example, because Document implements IStorable , you can access the IStorable methods and property through any Document instance: Document doc = new Document("Test Document"); doc.

WHAT IS interface in Delphi?

An object interface, or simply interface, defines methods that can be implemented by a class. Interfaces are declared as classes, but cannot be directly instantiated and do not have their own method definitions.


1 Answers

Instead of relying on Delphi's internal object layout you could also have your objects implement another interface which would simply return the object. This, of course, only works if you have access to the source code of the objects to begin with, but you probably shouldn't even use these hacks if you don't have access the source code of the objects.

interface 

type
  IGetObject = interface
    function GetObject: TObject;
  end;

  TSomeClass = class(TInterfacedObject, IGetObject)
  public
    function GetObject: TObject;
  end;

implementation

function TSomeClass.GetObject: TObject;
begin
  Result := Self;
end;
like image 151
Lars Truijens Avatar answered Sep 16 '22 15:09

Lars Truijens