Delphi TRttiType.GetMethods return zero TRttiMethod instances

折月煮酒 提交于 2019-12-11 07:34:25

问题


I've recently been able to fetch a TRttiType for an interface using TRttiContext.FindType using Robert Loves "GetType"-workaround ("registering" the interface by an explicit call to ctx.GetType, e.g. RType := ctx.GetType(TypeInfo(IMyPrettyLittleInterface));).

One logical next step would be to iterate the methods of said interface. Consider

program rtti_sb_1;
{$APPTYPE CONSOLE}
uses
  SysUtils, Rtti, mynamespace in 'mynamespace.pas';
var
  ctx:      TRttiContext;
  RType:    TRttiType;
  Method:   TRttiMethod;
begin
  ctx := TRttiContext.Create;
  RType := ctx.GetType(TypeInfo(IMyPrettyLittleInterface));
  if RType <> nil then begin
    for Method in RType.GetMethods do
      WriteLn(Method.Name);
  end;
  ReadLn;
end.

This time, my mynamespace.pas looks like this:

IMyPrettyLittleInterface = interface
  ['{6F89487E-5BB7-42FC-A760-38DA2329E0C5}']
  procedure SomeProcedure;
end;

Unfortunately, RType.GetMethods returns a zero-length TArray-instance. Are there anyone able to reproduce my troubles? (Note that in my example I've explicitly fetched the TRttiType using TRttiContext.GetType, not the workaround; the introduction is included to warn readers that there might be some unresolved issues regarding rtti and interfaces.) Thanks!


回答1:


I just traced through what's going on, and in TRttiInterfaceType.Create, line 5774, it says:

hasRtti := ReadU16(P);
if hasRtti = $FFFF then
  Exit;

And in both your interface, and IInterface which it inherits from, HasRtti reads as $FFFF. So apparently no RTTI is being generated for the interface's methods, and this is even true for the base Interface type. I don't know why. Not sure who would know why, aside from Barry Kelly.




回答2:


There are certain compiler directives sometimes needed to generate RTTI, like M+. Perhaps you just have to set one of those?




回答3:


Dave was right after all. As it turns out, the interface must be surrounded by a {$M+}/{$M-}-clause. Compiling with

{$M+}
IMyPrettyLittleInterface = interface
  ['{6F89487E-5BB7-42FC-A760-38DA2329E0C5}']
  procedure SomeProcedure;
end;
{$M-}

does it.



来源:https://stackoverflow.com/questions/3004045/delphi-trttitype-getmethods-return-zero-trttimethod-instances

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