Reputation: 3402
In a Delphi program, have the following pattern:
TDelegate=reference to procedure(const Arg: TMyType);
TRouter = class
...
public
procedure RegisterHandler(const route: string: handler: TDelegate);
end;
THandlerContainer = class
public
function getDelegate: TDelegate;
procedure register(const Router: TRouter);
end; // class
...
procedure THandlerContainer.register(const router: TRouter)
begin
router.RegisterHandler('route', getDelegate);
end;
Basically, I'm registering function references to be used to handle some message handling (based on the "route" string).
I would like to simplify the pattern for my coworkers so that they do not have to call router.RegisterHandler themselves for each implementation but simply have to add an attribute to their class and then pass an instance to a method of TRouter that will use RTTI to find all method decorated by that attribute and register them.
I have therefore created a simple attribute RegisterMessageHandlerAttribute
for that decoration (with a custom constructor for receiving the routing string) and wrote a method of TRouter that uses the RTTI to find all method decorated with that atribute:
function TRouter.RegisterHandlers(const HandlerContainerClass:
TObject);
var
RTTIContext: TRttiContext;
RttiType : TRttiType;
prop: TRttiMethod;
Attr: TCustomAttribute;
begin
RTTIContext := TRttiContext.Create;
try
RttiType := RTTIContext.GetType(HandlerContainerClass);
if assigned(RttiType) then
begin
for prop in RttiType.GetMethods do
begin
for Attr in Prop.GetAttributes do
begin
if (Attr is RegisterMessageHandlerAttribute) then
begin
Self.RegisterHandler(
(Attr as RegisterMessageHandlerAttribute).Route,
TDelegate(Prop.Invoke(HandlerContainerClass, []).AsPointer); // <--- this fails
);
end;
end;
end;
end;
finally
RTTIContext.Free;
end;
result := Handlers.ToArray;
end;
Unfortunately, the compilers complains on the line where I retrieve the lambda by calling the method:
TDelegate(Prop.Invoke(HandlerContainerClass, []).AsPointer);
...
[dcc32 Error] GIT.MessageQueue.Router.pas(169): E2089 Invalid typecast
My problem is that I have no idea how to take the TValue type returned by Prop.Invoke and use it as a function reference of type TDelegate.
Upvotes: 2
Views: 430
Reputation: 21713
Just use .AsType<TDelegate>()
- this returns the content of the TValue
as TDelegate
. That function is also making sure that you don't turn something that is inside the TValue
into something that is not explicitly assignment compatible (not like Variants do). But since that is the exact return type of your function it will just work.
P.S. You need to type the parentheses explicitly because otherwise you might get an E2010 error from the compiler.
Upvotes: 5