How to find index of a method in an interface?

微笑、不失礼 提交于 2019-12-10 17:18:24

问题


How can I find index of procedure/function which is defined in Interface? Can it be done with RTTI?


回答1:


First of all we need to enumerate the methods of the interface. Unfortunately this program

{$APPTYPE CONSOLE}

uses
  System.SysUtils, System.Rtti;

type
  IMyIntf = interface
    procedure Foo;
  end;

procedure EnumerateMethods(IntfType: TRttiInterfaceType);
var
  Method: TRttiMethod;
begin
  for Method in IntfType.GetDeclaredMethodsdo
    Writeln('Name: ' + Method.Name + 'Index: ' + IntToStr(Method.VirtualIndex));
end;

var
  ctx: TRttiContext;

begin
  EnumerateMethods(ctx.GetType(TypeInfo(IMyIntf)) as TRttiInterfaceType);
end.

produces no output.

This question covers this issue: Delphi TRttiType.GetMethods return zero TRttiMethod instances.

If you read down to the bottom of that question an answer states that compiling with {$M+} will lead to sufficient RTTI being emitted.

{$APPTYPE CONSOLE}

{$M+}

uses
  System.SysUtils, System.Rtti;

type
  IMyIntf = interface
    procedure Foo(x: Integer);
    procedure Bar(x: Integer);
  end;

procedure EnumerateMethods(IntfType: TRttiInterfaceType);
var
  Method: TRttiMethod;
begin
  for Method in IntfType.GetDeclaredMethods do
    Writeln('Name: ' + Method.Name + 'Index: ' + IntToStr(Method.VirtualIndex));
end;

var
  ctx: TRttiContext;

begin
  EnumerateMethods(ctx.GetType(TypeInfo(IMyIntf)) as TRttiInterfaceType);
end.

The output is:

Name: FooIndex: 3
Name: BarIndex: 4

Remember that all interfaces derive from IInterface. So one might expect its members to appear. However, it seems that IInterface is compiled in {$M-} state. It also seems that the methods are enumerated in order, although I've no reason to believe that is guaranteed.

Thanks to @RRUZ for pointing out the existence of VirtualIndex.



来源:https://stackoverflow.com/questions/27969212/how-to-find-index-of-a-method-in-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!