How to cast a Interface to a Object in Delphi

Solution 1:

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;

Solution 2:

You are right. Beginning with Delphi 2010, you are able to use the as operator, e.g. via aObject := aInterface as TObject or even aObject := TObject(aInterface).

This as operator use a special hidden interface GUID (ObjCastGUID) to retrieve the object instance, calling an enhanced version of TObject.GetInterface, which does not exist prior to Delphi 2010. See source code of System.pas unit to see how it works.

I've published some code working for Delphi 6 up to XE2, including Delphi 2009.

See http://blog.synopse.info/post/2012/06/13/Retrieve-the-object-instance-from-an-interface