Convert the method pointer to an integer, then call it

I wonder if this is possible or not, if so, how? Sample code.

  • How to save a pointer to an object method as an integer value ?
  • How to convert this integer value back to the "method pointer" and call it ?

What I want to do is to store the "method pointer" in the integer value of the tag of an object derived from TComponent, and after a while call the stored method. You can assume that all methods encountered have the same definition.

Thank!

+5
source share
2 answers

, ...

var
  Method: ^TNotifyEvent;
begin
//Create New method 
  GetMem(Method, SizeOf(TNotifyEvent));
//Init target Tag
  Tag := Integer(Method);

//Store some method
  Method^ := Button1Click;

//call stored method
  Method := (Pointer(Tag));
  Method^(self);

//And don't forget to call in to object destructor...
  if Tag <> 0 then
    FreeMem(pointer(Tag));
+5

, . TMethod:

TMethod = record
  Code, Data: Pointer;
end;

Code - , Data - Self, . , Int64, , , .

TMethod , GetMem, Tag, , .

+9

All Articles