代码之家  ›  专栏  ›  技术社区  ›  Yona

如何在Delphi中向对象转换接口

  •  12
  • Yona  · 技术社区  · 15 年前

    在Delphi2009中,我引用了 IInterface 我想把它投射到 TObject

    使用 TObject(IInterface)

    我的搜寻让我找到 a function that should do the trick ,但这对我不起作用,我在尝试对返回的对象调用方法时得到AV。

    我真的不能修改类,我知道这会破坏OOP

    6 回复  |  直到 15 年前
        1
  •  19
  •   Lars Truijens    15 年前

    与依赖Delphi的内部对象布局不同,您还可以让对象实现另一个接口,该接口只返回对象。当然,这只在你有权访问对象的源代码时才有效,但是如果你没有权访问对象的源代码,你可能甚至不应该使用这些黑客。

    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;
    
        2
  •  18
  •   Arnaud Bouchez    14 年前

    你是对的。从Delphi2010开始,您可以使用as运算符,例如通过 aObject := aInterface as TObject 甚至 aObject := TObject(aInterface)

    这个 as 运算符使用特殊的隐藏接口GUID( ObjCastGUID )要检索对象实例,请调用 TObject.GetInterface System.pas 看看它是怎么工作的。

    我已经为Delphi6到XE2发布了一些代码, including Delphi 2009

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

        3
  •  4
  •   Daniel Maurić    9 年前

    当您知道实现对象是 TComponent 后裔。

    你可以使用 IInterfaceComponentReference 接口,在 Classes

    IInterfaceComponentReference = interface
      ['{E28B1858-EC86-4559-8FCD-6B4F824151ED}']
      function GetComponent: TComponent;
    end;
    

    然后在 t部件 (并执行返回 self ):

      TComponent = class(TPersistent, IInterface, IInterfaceComponentReference)
    

    知道 实现对象是 t部件 然后你可以这样做:

    function InterfaceToComponent(const AInterface: IInterface): TComponent;
    var
      vReference: IInterfaceComponentReference;
    begin
      if Supports(AInterface, IInterfaceComponentReference, vReference) then
        result := vReference.GetComponent
      else
        result := nil;
    end;
    
        4
  •  3
  •   Ritsaert Hornstra    15 年前

    注意,接口“实例”可以用另一种语言实现(它们是COM兼容的)和/或可能是进程外内容的存根等。

    总而言之:一个接口实例只同意接口而不同意其他任何东西,当然不是作为Delphi TObject实例实现的

        5
  •  2
  •   500 - Internal Server Error    15 年前

    GetImplementingObject是否返回NIL?

        6
  •  -1
  •   MajidTaheri    14 年前
    var
      N, F: NativeInt; // NativeInt is Integer(in delphi 32bit ) 
      S: TObject;
    begin
      N := NativeInt(Args[0].AsInterface) - 12; 
      {subtract 12 byte to get object address(in x86 ,1 interface on class) }
      S := TObject(N);    
      writeln(S.ToString);
    
    end;