Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of a method in an interface?

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

like image 662
John Lewis Avatar asked Oct 19 '22 19:10

John Lewis


1 Answers

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.

like image 167
David Heffernan Avatar answered Oct 22 '22 22:10

David Heffernan