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 encapsulation of classes, 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:
Class ()
{
Static void a (A *); // static function
Void B (); // non-static function
}
Void A: A (A * pthis)
{
Pthis-> B (); // call a non-static function in a static function
}
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 ()
{
Static void a (); // static callback function
Void B (); // non-static function
Static A * pthis; // static object pointer
}
A * A: pthis = NULL;
A: A () // The constructor assigns this pointer to pthis so that the callback function can access this object through the pthis pointer.
{
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 ()
{
Static void a (); // static callback function
Void B (); // non-static function
Int m_id; // ID of the object in the list
Static int m_sid; // the ID of the current static object. (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;
A: A () // The constructor assigns this pointer to pthis so that the callback function can access this object through the pthis pointer.
{
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;
A * pthis = NULL;
If (m_map.lookup (m_sid, pthis ))
{
Pthis-> B (); // call non-static functions in the callback function
};
}