Delphi Rtti用于通用上下文中的接口 [英] Delphi Rtti for interfaces in a generic context

查看:147
本文介绍了Delphi Rtti用于通用上下文中的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于框架,我写了一个包装器,它接受任何对象,接口或记录类型来探索其属性或字段。课程声明如下:

for a framework I wrote a wrapper which takes any object, interface or record type to explore its properties or fields. The class declaration is as follows:

TWrapper<T> = class 
private
  FType : TRttiType;
  FInstance : Pointer;
  {...}
public
  constructor Create (var Data : T);
end;

在构造函数中,我尝试获取类型信息以进一步处理步骤。

In the constructor I try to get the type information for further processing steps.

constructor TWrapper<T>.Create (var Data : T);
begin
FType := RttiCtx.GetType (TypeInfo (T));
if FType.TypeKind = tkClass then
  FInstance := TObject (Data)
else if FType.TypeKind = tkRecord then
  FInstance := @Data
else if FType.TypeKind = tkInterface then
  begin
  FType := RttiCtx.GetType (TObject (Data).ClassInfo); //<---access violation
  FInstance := TObject (Data);
  end
else
  raise Exception.Create ('Unsupported type');
end;

我不知道这个访问冲突是否是delphi编译器中的一个错误(我在使用XE)。
经过进一步的调查,我写了一个简单的测试函数,它显示,要求类名也产生这个异常:

I wonder if this access violation is a bug in delphi compiler (I'm using XE). After further investigation I wrote a simple test function, which shows, that asking for the class name produces this exception as well:

procedure TestForm.FormShow (Sender : TObject);
var
  TestIntf : IInterface;
begin
TestIntf    := TInterfacedObject.Create;
OutputDebugString(PChar (TObject (TestIntf).ClassName)); //Output: TInterfacedObject
Test <IInterface> (TestIntf);
end;

procedure TestForm.Test <T> (var Data : T);
begin
OutputDebugString(PChar (TObject (Data).ClassName)); //access violation
end;

有人可以解释一下,有什么问题吗?我也尝试过没有var参数的程序,也不工作。当使用非通用过程时,一切都可以正常工作,但是为了简化包装器的使用,通用解决方案将是很好的,因为它适用于对象和记录方式相同。

Can someone explain me, what is wrong? I also tried the procedure without a var parameter which did not work either. When using a non generic procedure everything works fine, but to simplify the use of the wrapper the generic solution would be nice, because it works for objects and records the same way.

Christian

Christian

推荐答案

您的代码包含两个错误假设:

Your code contains two wrong assumptions:


  • 您可以从Interfaces获得有意义的 RTTI / strike>哎呀,你可以从界面类型获得RTTI

  • 一个接口总是由Delphi对象实现的(因此你尝试从RTTI中提取RTTI支持Delphi对象)。

  • That you can obtain meaningful RTTI from Interfaces. Oops, you can get RTTI from interface types.
  • That a Interface is always implemented by a Delphi object (hence your attempt to extract the RTTI from the backing Delphi object).

这两个假设都是错误的。接口是非常简单的VIRTUAL METHOD表,对他们来说很少有魔法。 由于界面如此狭义地定义,它不可能具有 RTTI 。除非你自己实现你自己的 RTTI 的变体,否则你不应该。 LE:接口本身不能携带类型信息一个TObject是,但是如果提供了一个IInterface,TypeOf()运算符可以获得TypeInfo

Both assumptions are wrong. Interfaces are very simple VIRTUAL METHOD tables, very little magic to them. Since an interface is so narrowly defined, it can't possibly have RTTI. Unless of course you implement your own variant of RTTI, and you shouldn't. LE: The interface itself can't carry type information the way an TObject does, but the TypeOf() operator can get TypeInfo if provided with a IInterface

你的第二个假设也是错误的,但不太符合要求。在Delphi世界中,大多数接口将由Delphi对象实现,除非您以其他编程语言编写的DLL获取接口:Delphi的接口是COM兼容的,所以它的实现可以从任何其他COM兼容语言反之亦然。但是,由于我们在这里讲Delphi XE,您可以使用这种语法以直观可读的方式为其实现对象投放一个界面:

Your second assumption is also wrong, but less so. In the Delphi world most interfaces will be implemented by Delphi objects, unless of course you obtain the interface from a DLL written in an other programming language: Delphi's interfaces are COM-compatible, so it's implementations can be consumed from any other COM-compatible language and vice versa. But since we're talking Delphi XE here, you can use this syntax to cast an interface to it's implementing object in an intuitive and readable way:

TObject := IInterface as TObject;

即使用作为运算符。 Delphi XE有时会自动转换这种类型的硬转换:

that is, use the as operator. Delphi XE will at times automagically convert a hard cast of this type:

TObject := TObject(IInterface);

提到的但是我不喜欢这个魔法,因为它看起来很直观,在旧版本的Delphi中表现不一样。

to the mentioned "as" syntax, but I don't like this magic because it looks very counter-intuitive and behaves differently in older versions of Delphi.

code>回到它的实现对象也是从另一个角度错误的:它将显示实现对象的属性,不仅仅是与接口有关的属性,而且这是非常错误的,因为您正在使用Interfaces首先隐藏这些实现细节!

Casting the Interface back to it's implementing object is also wrong from an other perspective: It would show all the properties of the implementing object, not only those related to the interface, and that's very wrong, because you're using Interfaces to hide those implementation details in the first place!

只是为了好玩,这里是一个由Delphi对象支持的界面的快速演示。由于接口只不过是指向虚拟方法表的指针,所以我将构造虚拟方法表,创建一个指向它的指针,并将指针转换为所需的接口类型。我的虚假虚拟方法表中的所有方法指针都是使用全局函数和过程实现的。试想从我的 i2 界面中提取RTTI!

Just for fun, here's a quick demo of an interface that's not backed by an Delphi object. Since an Interface is nothing but an pointer to a virtual method table, I'll construct the virtual method table, create a pointer to it and cast the the pointer to the desired Interface type. All method pointers in my fake Virtual Method table are implemented using global functions and procedures. Just imagine trying to extract RTTI from my i2 interface!

program Project26;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type

  // This is the interface I will implement without using TObject
  ITestInterface = interface
  ['{CFC4942D-D8A3-4C81-BB5C-6127B569433A}']
    procedure WriteYourName;
  end;

  // This is a sample, sane implementation of the interface using an
  // TInterfacedObject method
  TSaneImplementation = class(TInterfacedObject, ITestInterface)
  public
    procedure WriteYourName;
  end;

  // I'll use this record to construct the Virtual Method Table. I could use a simple
  // array, but selected to use the record to make it easier to see. In other words,
  // the record is only used for grouping.
  TAbnormalImplementation_VMT = record
    QueryInterface: Pointer;
    AddRef: Pointer;
    ReleaseRef: Pointer;
    WriteYourName: Pointer;
  end;

// This is the object-based implementation of WriteYourName
procedure TSaneImplementation.WriteYourName;
begin
  Writeln('I am the sane interface implementation');
end;

// This will implement QueryInterfce for my fake IInterface implementation. All the code does
// is say the requested interface is not supported!
function FakeQueryInterface(const Self:Pointer; const IID: TGUID; out Obj): HResult; stdcall;
begin
  Result := S_FALSE;      
end;

// This will handle reference counting for my interface. I am not using true reference counting
// since there is no memory to be freed, si I am simply returning -1
function DummyRefCounting(const Self:Pointer): Integer; stdcall;
begin
  Result := -1;
end;

// This is the implementation of WriteYourName for my fake interface.
procedure FakeWriteYourName(const Self:Pointer);
begin
  WriteLn('I am the very FAKE interface implementation');
end;

var i1, i2: ITestInterface;
    R: TAbnormalImplementation_VMT;
    PR: Pointer;

begin
  // Instantiate the sane implementation
  i1 := TSaneImplementation.Create;

  // Instantiate the very wrong implementation
  R.QueryInterface := @FakeQueryInterface;
  R.AddRef := @DummyRefCounting;
  R.ReleaseRef := @DummyRefCounting;
  R.WriteYourName := @FakeWriteYourName;
  PR := @R;
  i2 := ITestInterface(@PR);

  // As far as all the code using ITestInterface is concerned, there is no difference
  // between "i1" and "i2": they are just two interface implementations.
  i1.WriteYourName; // Calls the sane implementation
  i2.WriteYourName; // Calls my special implementation of the interface

  WriteLn('Press ENTER to EXIT');
  ReadLn;
end.

这篇关于Delphi Rtti用于通用上下文中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆