
Unfortunately, the major problem with function pointers is that you can't send any extra data with them, so there isn't a good way to package up the A pointer and send it to setCallback. However, most C callback interfaces also store a user-defined void* for callback data, which I'm hoping you omitted for brevity. With such a void*, you can do something like this:
In this particular case, there was unfortunatelly no additional parameter to pass private data to the C callback registration function.
// C function declared in some library struct E; extern void setCallBack(void (*callback_fct)(E*), void* data);
typedef boost::function<void (E*)> callback;
class A{ public: void init(); void callBack(E* e);
private: callback* cb;
// Trampoline function static void do_callback(E* e, void* data) { (*static_cast<callback*>(data))(e); } };
void A::init() { cb = new callback(boost::bind(&A::callBack, this, _1)); setCallback(&do_callback, cb); }
Doug
This is a very useful solution that I am likely going to employ if I have C function pointers that take also private data. Thanks for the suggestion. Probably more as a site note (curiosity if you will on a language level): #include <boost/function.hpp> int someFoo(int val) {return val + 5;} void someMain() { boost::function<int (int)> bptr = someFoo; int (*cptr)(int) = someFoo; bptr(5); cptr(5); if (bptr == cptr) printf("equal\n"); } The above code snipet does not compile as the types of bptr and cptr are not the same and thus their values cannot be compared although they are identical. I have not followed the C++ Spec evolution closely and am only familar with what appears to be the 98 spec. Are there any plans to uniformize this on the language level? This would allow interfacing C style code with the nice boost function pointers in a much cleaner way. Thanks again for your answer, -Thomas