Click here to Skip to main content
15,901,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, does someone know some nice
tutorial about using C++ member functions as callbacks using function pointers??
Posted
Updated 21-Feb-13 0:37am
v2

IMO, member function pointer is not very different from ordinary function pointer except the member function pointer is bound with the class scope. These are some of the links.

http://support.microsoft.com/kb/94579

http://www.tutok.sk/fastgl/callback.html

http://blogs.msdn.com/b/oldnewthing/archive/2004/02/09/70002.aspx
 
Share this answer
 
Hi,

this shall be quite easy. Member callback function shall be static and should accept at least one parameter that is the pointer the callback object, which is an instance of the class that has the callback method.

The following class has a callback method _MyCallbackMethod:

C++
class CMyCallbackClass
{
public:
   static void __stdcall _MyCallbackMethod(void* pObject, int iMyParam>)
   {
       CMyCallbackClass* pThis = reinterpret_cast<cmycallbackclass*>(pObject);
       pThis->MyCallbackMethod(iMyParam);
   }   
   
   void MyCallbackMethod(int iMyParam)
   {
       // your code here
   }
};

And finally, you give another object a pointer to the static method _MyCallbackMethod to another class:
C++
class X
{
public:
   void SetCallbackMethod(void (*methoPtr)(int))
   {
      this->m_pPtr = methoPtr;
   }
};

The X class will call the callback in the following way:
C++
this->pPtr(10);


Best regards,
J. K.
 
Share this answer
 
Comments
H.Brydon 21-Feb-13 12:01pm    
Good answer - +5

[Important part is that it needs to be static since you can control scope but can't get 'this' context.]
[no name] 21-Feb-13 17:17pm    
Hi, thanks for your response. But should it not be:
void SetCallbackMethod(void (*methoPtr)(void*)(int)) instead of:
void SetCallbackMethod(void (*methoPtr)(int))??

and ps. one more question, how would you define m_pPtr in class x? e.g., its type etc.?? Thanks.
[no name] 22-Feb-13 10:05am    
pps. so it's not possible to avoid wrapper functions with member function pointers right?? in case if you want to use a pointer to generic class member function ...??
Look under the keyword "Delegate". There are several nice articles about this subject here on CodeProject. A delegate is in simple words the combination of a member function pointer and an object pointer. It allows you to call a certain member function of a specific object from just a single entity.

Delegates, when implemented right, are much easier to deal with than the classical C++ member function pointers.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900