|
Boost Users : |
From: Douglas Gregor (gregod_at_[hidden])
Date: 2003-02-11 00:01:47
On Monday 10 February 2003 04:22 pm, Thomas Pollinger wrote:
> Apologies if this topic has already been discussed. I have looked around
> on various mailing lists, in addition I have tried to make it work with
> the current C++ STL standard with std::mem_fun and std::bind1st but with
> no success.
>
> The problem is basically to bind a member function pointer with an
> instance of its declaring class and to assign the result to an existing
> C library function that expects a C style function pointer. This
> certainly works for ordinary C functions and static C++ functions,
> however fails for bound member function pointers.
>
> Here is what I am trying to achieve:
>
> #include <boost/bind.hpp>
>
> // C function declared in some library
> struct E;
> extern void setCallBack(void (*callback_fct)(E*));
>
> class A {
> public:
> void init();
> void callBack(E *e);
> ....
> };
>
> void A::init() {setCallBack(boost::bind(&A::callBack, this));}
> void A::callBack(E *e) {...}
>
> I tried also using the STL calls, but without success either:
> ...
> setCallBack(std::bind1st(std::mem_fun(&A::callBack), this));
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:
// 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
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net