The callback function calls non-static member variables or non-static member functions in the class.
[Question] How do I encapsulate callback functions in a class?
A. the callback function can only be global or static;
B. Global functions will damage the class encapsulation, so they will not be used;
C. Static functions can only be static members of the callback class. They cannot be non-static members of the callback class.
1. How to make non-static members of the callback class of the static function.
A. Declare a static function a () and pass the class instance object pointer as a parameter. For example:
ClassA (){Static VoidA (*);//Static FunctionsVoidB ();//Non-static functions}VoidA: A (*Pthis) {pthis-> B ();//Call non-static functions in static functions}
B. Access non-static members in the callback function
Since the callback function is often fixed and does not accept the * pthis Parameter
For example, callback mytimerproc (hwnd, uint umsg, uint idevent, DWORD dwtime );
[Solution 1]: This solution has problems when there are multiple class instance objects. The reason is that the pthis pointer can only point to one object.
Class A (){ Static Void A (); // Static callback function Void B (); // Non-static functions Static A * pthis; // Static object pointer } // The constructor assigns this pointer to pthis so that the callback function can access this object through the pthis pointer. A * A: pthis = NULL; A: A () {pthis = This ;} Void A: (){ If (Pthis = Null) Return ; Pthis -> B (); // Call non-static functions in the callback function }
[Solution 2]: This solution solves the problem of solution 1 when multiple class instance objects exist. Store all object addresses in the ing table, and each object saves its own ID number.
Typedef cmap <uint, uint, A *, A *> Camap; Class A (){ Static Void A (); // Static callback function Void B (); // Non-static functions Int M_id; // ID of this object in the list Static Int M_sid; // Static current Object ID. (if necessary, assign m_id to m_sid to call this object function) Static Camap m_map; // Static object ing table } Camap A: m_map; Int A: m_sid = 0 ; // The constructor assigns this pointer to pthis so that the callback function can access this object through the pthis pointer. A: (){ If (M_map.isempty () {m_id = 1 ;} Else {M_id = M_map.getcount () + 1 ;} M_map.setat (m_id, This );} Void A: (){ If (M_map.isempty ()) Return ; * Pthis = NULL; If (M_map.lookup (m_sid, pthis) {pthis -> B (); // Call non-static functions in the callback function };}
[Thank you for your reference]
1. The callback function calls non-static member variables or non-static member functions in the class.