Method pointers

Top  Previous  Next

What is translated > Method pointers

 

Delphi's event handling is implemented by means of method pointers. Such  method pointers are declared by addition of the words "of object" to a procedural type name. E.g.

 

TNotifyEvent = procedure(Sender: TObject) of object;

 

According to the Delphi help "a method pointer is really a pair of pointers; the first stores the address of a method, and the second stores a reference to the object the method belongs to". Such method pointers can point to any member functions in any class. For example by means of a method pointer  the event handling of a special instance of a control - e.g. TButton - can be delegated to the instance of another class - e.g. TForm .

 

Delphi's method pointers cannot be translated as standard C++ member function pointers, because they can point to other member functions of the same inheritance hierarchy only. That's why Borland has extended the standard C++ syntax by the keyword __closure. With this keyword method pointers with the same properties as Delphi's method pointers can be declared in Borland C++. E.g. the event above is:

 

typedef void __fastcall (__closure *TNotifyEvent)(TObject* Sender);

 

 

For other compilers C++Builder closures can be substituted by means of the new standard functions in C++11. The definition of the TNotifyEvent above then becomes to:

 

typedef std::function<void (TObject*)> TNotifyEvent;

 

 

A class instance - e.g. TButton* pButton - can be bound to a member function of this signature - e.g. TButton::OnClick - by means of std::bind1st and std::mem_fun:

 

 

TNotifyEvent ev = std::bind1st(std::mem_fun(&TMyButton::OnClickHandle), pButton);

 

 

Once a handler is assigned, further operations with the event are looking as simple as in the original Delphi code. E.g.:

 

// calling the event

Button1.OnClick(Button1); ->  Button1->OnClick(Button1); 

 

// assigning the event handler to another button

Button2.OnClick = Button1.OnClick; -> Button2->OnClick = Button1->OnClick;

 

 

Remark: In contrast to Delphi2Cpp the first version of Delphi2Cpp used a similar solution from Tamas Demjen :

 

http://tweakbits.com/articles/events/index.html

 

 

 

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content