使用Delphi RTTI获取接口的字符串名称 [英] Getting the string name of an interface using Delphi RTTI

查看:607
本文介绍了使用Delphi RTTI获取接口的字符串名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经证明我可以使用Delphi 2010从其GUID获取接口的名称(例如,IMyInterface转换为字符串'IMyInterface'。我想在Delphi 7中实现这一点(兼容性)。这是可能的吗? ?或者是否有基本的编译器限制。

I have proved that I can get the name of an interface from its GUID using Delphi 2010 (eg IMyInterface converted to the string 'IMyInterface'. I'd like to achieve this in Delphi 7 (for compatibility). Is this possible? Or are there fundamental compiler limitations.

推荐答案

是的,你可以得到它,以下显示使用IExample类型如何获得名称。
旧的Delphi 7 RTTI是通过TypInfo单元完成的。

Yes you can get it, the following shows using the IExample type how you can get the name. The old Delphi 7 RTTI was done through the TypInfo Unit.

program Project6;
{$APPTYPE CONSOLE}
uses
  SysUtils,TypInfo;

type
  IExample = interface
    ['{4902F666-F3FC-4999-BD8C-F226851201D6}']
    procedure blah;
  end;


begin
  Writeln(GetTypeName(TypeInfo(IExample)));
  readln
end.

刚刚注意到你说你想从GUID获得它而不仅仅是这需要一个GUID注册表来表示类型.Delph中的RTTI i 7可用于获取类型。

Just noticed you said you wanted to get it from the GUID and not just the type. This would require a registry of GUID to types. The RTTI in Delphi 7 can be used to get the type.

以下将使用IExample返回guid。

The following will take IExample return the guid.

Writeln(GUIDToString(GetTypeData(TypeInfo(IExample)).Guid));

这是一个示例注册表,它将接口的TypeInfo()映射到它的GUID。
它可以进行优化,但我这样做是为了说明这个概念。

Here is an example registry that would Map TypeInfo() of an Interface to it's GUID. It could be optimized but I did it to illustrate the concept.

unit Unit11;

interface
uses
  TypInfo,SysUtils, Contnrs;

type

  TGuidMap = class(TObject)
    Guid : TGUID;
    TypeInfo : PTypeInfo;
  end;

procedure RegisterInterface(InterfaceType : PTypeInfo);

function GetInterfaceType(Guid : TGUID) : PTypeInfo;

implementation
var
  GuidMapList : TObjectList;

procedure RegisterInterface(InterfaceType : PTypeInfo);
var
 Map : TGuidMap;
begin
  Map := TGuidMap.Create;
  Map.TypeInfo := InterfaceType;
  Map.Guid := GetTypeData(InterfaceType).Guid;
  GuidMapList.Add(Map);
end;

function GetInterfaceType(Guid : TGUID) : PTypeInfo;
var
 I : Integer;
begin
 result := nil;
 for I := 0 to GuidMapList.Count - 1 do
 begin
   if IsEqualGUID(TGuidMap(GuidMapList.Items[I]).Guid,Guid) then
   begin
     result := TGuidMap(GuidMapList.Items[I]).TypeInfo;
     break;
   end;
 end;
end;

Initialization
 GuidMapList := TObjectList.Create(true);
finalization
 GuidMapList.Free;
end.

要将项目添加到注册表,您可以调用

To Add an item to the registry you would then call

   RegisterInterface(TypeInfo(IExample));

这篇关于使用Delphi RTTI获取接口的字符串名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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