Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert method pointer to integer, then call it

Tags:

delphi

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!

like image 329
Edwin Yip Avatar asked Dec 20 '10 03:12

Edwin Yip


1 Answers

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.

like image 141
Zoë Peterson Avatar answered Sep 23 '22 01:09

Zoë Peterson