Reputation: 10372
I want to handle a TRttiMethod
as anonymous method. How could I do this?
Here is a simplified example of how I wish things to work:
Interface:
TMyClass = class
public
// this method will be acquired via Rtti
procedure Foo;
// this method shall return above Foo as anonymous method
function GetMethodAsAnonymous: TProc;
end;
Implementation:
function TMyClass.GetMethodAsAnonymous: TProc;
var
Ctx: TRttiContext;
RttiType: TRttiType;
RttiMethod: TRttiMethod;
begin
Ctx := TRttiContext.Create;
try
RttiType := Ctx.GetType(Self.ClassType);
RttiMethod := RttiType.GetMethod('Foo');
Result := ??????; // <-- I want to put RttiMethod here - but how?
finally
Ctx.Free;
end;
end;
Upvotes: 4
Views: 792
Reputation: 163247
If you really want an anonymous method, then make an anonymous method:
Result := procedure
begin
RttiMethod.Invoke(Self, []);
end;
You can also construct a simple method pointer:
var
Method: procedure of object;
TMethod(Method).Code := RttiMethod.CodeAddress;
TMethod(Method).Data := Self;
Result := Method;
The most direct way of course doesn't use RTTI at all:
Result := Foo;
Upvotes: 3