简体   繁体   中英

Convert method pointer to integer, then call it

I'm wondering if this the following is possible or not, if yes, how? Code example please.

  • How to store a pointer to a method of a object as an integer value ?
  • How to convert that integer value back to a 'method pointer' and call it ?

What I want to do is store a 'method pointer' in the integer Tag value of a TComponent-derived object, and sometime later call the stored method. You can assume all met methods have the same definition.

Thanks!

No, it's not possible. A method of object is equivalent to TMethod:

TMethod = record
  Code, Data: Pointer;
end;

The Code field is the address of the method, and the Data field is the hidden Self parameter that's passed into every object method. The record is the same size as an Int64, so if you cast it as a plain Integer you'll lose half of it.

You could allocate a TMethod record on the heap using GetMem and then store the address of that in the Tag property, as long as you remembered to free it when you're done with it.

You can do workaround, but it si not nice design...

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM