Class member function as callback using boost :: bind and boost :: function

I am working on setting a member function as a callback for the C library I am using. The C library sets callbacks as follows:

typedef int (*functionPointer_t)(myType1_t*, myType2_t*, myType3_t*); setCallback(param1, param2, functionPointer, param4) 

I would like to use boost :: bind (if possible) to pass a function pointer. I would prefer the specified function to be a member of the class instance, rather than a static member. For example.

 Class A { public: A(); protected: int myCallback(myType1_t*, myType2_t*, myType3_t*); //aka functionPointer_t } 

Can this be done using boost :: bind and boost :: function? Per How do I pass a member function of a class as a callback? (third answer), it seems that I can declare the following (somewhere or as a typedef):

 boost::function<int (A*, myType1_t*, myType2_t*, myType3*> myCallbackFunction 

And then somewhere in (ctor) call boost :: bind of this type and pass it to the C library call.

Is this possible, or have I left the base? Many thanks.

+7
c ++ boost boost-bind boost-function
source share
3 answers

Not. Functor types such as boost::function are not converted to function pointers for use with C callback mechanisms.

However, most C callback mechanisms have some kind of token mechanism, so your callback function (static) has some contextual information. You can use this to write a wrapper class that maps these tokens to functor objects and passes execution to the right:

 class CallbackManager { public: typedef boost::function<int (type1*, type2*, type3*)> callback; static void setCallback(CallbackManager::callback cb) { void *token = ::setCallback(staticCallback); callbacks[token] = callback_I; } static void staticCallback(void* token, type1* a, type2* b, type3* c) { return mcallbacks[token](a, b, c); } private: static std::map<void*, callback > callbacks; }; 
+5
source share

do not use the card, it provides service data at runtime and clutters the code with the static card.

use reinterpret_cast instead.

eg

 // clib.h typedef void (*CALLBACK_FUNC)(int code,void *param); void set_callback( CALLBACK_FUNC, void * param ); // ah class A { public: A() { ::set_callback( &A::static_callback, this); } private: static void static_callback(int code, void * param) { A* self = reinterpret_cast<A*>(param); self->callback( code ); } inline void callback( int code ) { // write you code here. } }; 
+1
source share

The problem with member functions is that they automatically get a pointer to an object instance as the first parameter - the "this" pointer. Therefore, you cannot use the member functions of the C callback function. You must have an AND object and a function pointer together to use the member function.

0
source share

All Articles