设为首页 加入收藏

TOP

Delphi判断某个类是否实现了某个接口
2017-10-10 12:05:21 】 浏览:4930
Tags:Delphi 判断 某个 是否 实现 接口

通过TObject.GetInterface可以获得对象的实例实现某个接口,前提条件是必须实例化对象后才能运行GetInterface

下面的方法可获取类是否实现了某个接口,并返回接口的偏移:

function FindInterface(AClass: TClass; GUID:TGUID; var Offset:NativeInt):Boolean;
var
  i : integer;
  InterfaceTable: PInterfaceTable;
  InterfaceEntry: PInterfaceEntry;
begin
  while Assigned(AClass) do
  begin
    InterfaceTable := AClass.GetInterfaceTable;
    if Assigned(InterfaceTable) then
    begin
      for i := 0 to InterfaceTable.EntryCount-1 do
      begin
        InterfaceEntry := @InterfaceTable.Entries[i];
        if InterfaceEntry.IID=GUID then
        begin
          Offset:=InterfaceEntry.IOffset;
          Exit(True);
        end;
      end;
    end;
    AClass := AClass.ClassParent;
  end;
end;

 下面我们看下通过偏移量的快速获得对象的接口,以及通过接口快速获取对象:

快速获取对象的接口:

type
  TSomeObject=class(TXXX, ISomeInterface)
  ......
  end;

var
  FItemObjectOffset:NativeInt;

//获取偏移量
FindInterface(TSomeObject, ISomeInterface, FItemObjectOffset)

var
  P:TSomeObject;
  Intf:ISomeInterface;
....................................

//通过对象直接获取接口
    PNativeInt(@Intf)^:=PNativeInt(@P)^+ FItemObjectOffset;
    Intf._AddRef;

  

快速通过接口获取对象

type
  TSomeObject=class(TXXX, ISomeInterface)
  ......
  end;

var
  FItemObjectOffset:NativeInt;

//获取偏移量
FindInterface(TSomeObject, ISomeInterface, FItemObjectOffset)

var
  P:TSomeObject;
  Intf:ISomeInterface;
....................................

//通过接口获取对象
  P:=TSomeObject(Pointer(PNativeInt(@Intf)^- FItemObjectOffset));

  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇[工具] Firemonkey Style 调色工.. 下一篇[示例] Firemonkey 不规则按钮实做

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目