2

私は最近、インターフェイスと 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}で見つけることができます。

質問: RTTI を使用して目的の型をキャストする方法はありますか? つまり、1) 文字列としての IChild の修飾名、および 2) IParent インターフェイスとしての TChild インスタンスへの参照を知ることから IChild.ChildMethod を呼び出す方法はありますか? (結局のところ、ハードコードされたキャストは問題なく動作します。これは可能なのでしょうか?) ありがとうございます!

4

1 に答える 1

2

これは、RTTI.pasのレイジーコーディングのかなり醜いインスタンスのように見えます。TValue内のインターフェイスのキャストを処理するConvIntf2Intf関数では、にキャストしているかどうかを明示的にチェックするだけですIInterface。その他のインターフェースは自動的にfalseを返します。GUIDを簡単に抽出して(インターフェイスにGUIDがある場合)、QueryInterface呼び出しを試みることができますが、何らかの理由でそれを実行しません。これをQCに報告します。

于 2010-06-10T19:13:25.810 に答える