【问题标题】:Delphi interface cast using TValue使用 TValue 进行 Delphi 接口转换
【发布时间】:2011-03-02 08:17:01
【问题描述】:

我最近对接口和 D2010 RTTI 进行了广泛的试验。我在运行时不知道接口的实际类型;虽然我可以使用字符串访问它的限定名称。

考虑以下几点:

program rtti_sb_1;
{$APPTYPE CONSOLE}
uses
  SysUtils, Rtti, TypInfo, mynamespace in 'mynamespace.pas';
var
  ctx:                  TRttiContext;
  InterfaceType:        TRttiType;
  Method:               TRttiMethod;
  ActualParentInstance: IParent;
  ChildInterfaceValue:  TValue;
  ParentInterfaceValue: TValue;
begin
  ctx := TRttiContext.Create;
  // Instantiation
  ActualParentInstance := TChild.Create as IParent;
  {$define WORKAROUND}
  {$ifdef WORKAROUND}
  InterfaceType := ctx.GetType(TypeInfo(IParent));
  InterfaceType := ctx.GetType(TypeInfo(IChild));
  {$endif}
  // Fetch interface type
  InterfaceType := ctx.FindType('mynamespace.IParent');
  // This cast is OK and ChildMethod is executed
  (ActualParentInstance as IChild).ChildMethod(100);
  // Create a TValue holding the interface
  TValue.Make(@ActualParentInstance, InterfaceType.Handle, ParentInterfaceValue);
  InterfaceType := ctx.FindType('mynamespace.IChild');
  // This cast doesn't work
  if ParentInterfaceValue.TryCast(InterfaceType.Handle, ChildInterfaceValue) then begin
    Method := InterfaceType.GetMethod('ChildMethod');
    if (Method <> nil) then begin
      Method.Invoke(ChildInterfaceValue, [100]);
    end;
  end;
  ReadLn;
end.

mynamespace.pas的内容如下:

{$M+}
IParent = interface
  ['{2375F59E-D432-4D7D-8D62-768F4225FFD1}']
  procedure ParentMethod(const Id: integer);
end;
{$M-}
IChild = interface(IParent)
  ['{6F89487E-5BB7-42FC-A760-38DA2329E0C5}']
  procedure ChildMethod(const Id: integer);
end;
TParent = class(TInterfacedObject, IParent)
public
  procedure ParentMethod(const Id: integer);
end;
TChild = class(TParent, IChild)
public
  procedure ChildMethod(const Id: integer);
end;

为了完整起见,实现如下

procedure TParent.ParentMethod(const Id: integer);
begin
  WriteLn('ParentMethod executed. Id is ' + IntToStr(Id));
end;
procedure TChild.ChildMethod(const Id: integer);
begin
  WriteLn('ChildMethod executed. Id is ' + IntToStr(Id));
end;

{$define WORKAROUND} 的原因可以在in this post 中找到。

问题:我有什么方法可以使用 RTTI 进行所需的类型转换?换句话说:有没有办法让我调用 IChild.ChildMethod,因为我知道 1)作为字符串的 IChild 的限定名称,以及 2)作为 IParent 接口的对 TChild 实例的引用? (毕竟,硬编码演员工作正常。这甚至可能吗?)谢谢!

【问题讨论】:

    标签: delphi interface casting rtti


    【解决方案1】:

    这看起来像是 RTTI.pas 中一个非常丑陋的惰性编码实例。在处理 TValue 中的接口转换的 ConvIntf2Intf 函数中,它仅显式检查您是否正在转换为 IInterface。任何其他接口都会自动返回 false。它可以轻松提取 GUID(如果您的界面有一个)并尝试 QueryInterface 调用,但无论出于何种原因它都不会这样做。我会将此报告给 QC。

    【讨论】:

    • 伙计,这很有道理!我真的不明白为什么这不起作用。再次救援! :) (+1) 我会在早上向 QC 报告。
    • 早晨来得比预期的要快...现在在 QC #85339 下进行了报告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 2020-06-07
    • 2021-11-27
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    相关资源
    最近更新 更多