Edwin Yip
Edwin Yip

Reputation: 4220

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.

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!

Upvotes: 6

Views: 8307

Answers (2)

GJ.
GJ.

Reputation: 10937

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

Upvotes: 9

Zo&#235; Peterson
Zo&#235; Peterson

Reputation: 13322

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.

Upvotes: 10

Related Questions