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


Delphi2Cpp supports a lightweight and fast solution for other compilers, that was found by Tamas Demjen :


His detailed explanation of his approach is in the file "Events.rtf": According to his solution the closure above has to be defined as:


typedef event1< void, TObject* > TNotifyEvent;


The return type and the parameters of the original member pointer become template arguments of an event class. Internally this class holds a pointer to  a standard C++ member function and to an instance of a class with this function. This makes the assignment of an event handler to an event looking complicated. A special Connect method has to be called instead of a simple assignment. However Delphi2Cpp creates the according code automatically for you. For example:





Here Button1.OnClick is an event of TButton, TAppManager is a class with the event handler Button1Click and AppManager is an instance of that class. 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



// assigning the event handler to another button

Button2.OnClick = Button1.OnClick; 






This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content