开发者

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 objec开发者_Go百科t, 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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜