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
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With