How to cast a Interface to a Object in Delphi

前端 未结 6 1033
南旧
南旧 2020-12-01 18:39

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

Using TObject(IInterface) obv

6条回答
  •  死守一世寂寞
    2020-12-01 19:20

    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;
    

提交回复
热议问题