How can I find index of procedure/function which is defined in Interface? Can it be done with RTTI?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With