Can I use a closure on an event handler (ie, TButton OnClick)

前端 未结 4 2009
迷失自我
迷失自我 2020-12-24 03:44

If I try to use a closure on an event handler the compiler complains with :

Incompatible types: \"method pointer and regular procedure\"

which I understand..

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-24 04:20

    In previous Delphi versions you could use a regular procedure as event handler by adding the hidden self pointer to the parameters and hard typecast it:

    procedure MyFakeMethod(_self: pointer; _Sender: TObject);
    begin
      // do not access _self here! It is not valid
      ...
    end;
    
    ...
    
    var
      Meth: TMethod;
    begin
      Meth.Data := nil;
      Meth.Code := @MyFakeMethod;
      Button1.OnClick := TNotifyEvent(Meth);
    end;
    

    I am not sure the above really compiles but it should give you the general idea. I have done this previously and it worked for regular procedures. Since I don't know what code the compiler generates for closures, I cannot say whether this will work for them.

提交回复
热议问题