Has anyone noticed that the accepted answer only works with trivial cases? The only way the <> :: target () function returns an object that can be attached to a C callback is if it was constructed with an object that can be associated with a C callback. If so, then you could bind it directly and skip the whole function <> nonsense to begin with.
If you think about it, there is no magic solution. The C-style callback is stored as a single pointer that points to executable code. Any non-trivial boost :: function <> will require at least two pointers: one for the executable code, the other for the data needed to configure the call (for example, the 'this' pointer, in the case of a related member function).
The proper way to use boost :: function and boost :: bind with C callbacks is to create a pad function that satisfies the callback signature, determines which function <> to call, and calls it. Typically, C callbacks will have some kind of void * for "user data"; that when you click on a function pointer:
typedef void (*CallbackType)(int x, void* user_data); void RegisterCallback(CallbackType cb, void* user_data); void MyCallback(int x, void* userData) { boost::function<void(int)> pfn = static_cast<boost::function<void(int)> >(userData); pfn(x); } boost::function<void(int)> fn = boost::bind(myFunction(5)); RegisterCallback(MyCallback, &fn);
Of course, if your callback signature does not include some sort of user data pointer, you're out of luck. But any callback that does not include a user data pointer is already unsuitable for most real-world scenarios and needs to be rewritten.
Ian Ni-Lewis Aug 10 '10 at 21:32 2010-08-10 21:32
source share