Search code examples
c++methodsstaticfunction-pointers

Pass a non-static method pointer as an argument to another method


Sorry to ask such a question as I'm sure it's been answered before, but I'm struggling to find an answer and it's not for the want of looking... anyway..

class foo
{
    void read(void (*func)(obj&))
    {
        // many things happen to obj...
        (*func)(obj);    // Calls the function pointer to the handler.
    }

};
class bar : public foo
{
    void handler(obj&)
    {
        // 
    }
};

void main()
{
    foo f;

    typedef void (foo::*funcptr)(obj&);
    funcptr ptr = &foo::handler;

    f.read(ptr);   ????
}

So basically, all I'm trying to do is pass the non-static member method called handler as a function pointer to the read method, so that when the callback is executed, the handler is called.

I've tried all sorts of ways to make this work and don't want to make static methods (for reasons I won't go into). I think I'm pretty close, but have sort of fallen over right at the end! Any help would be appreciated.


Solution

  • You cannot do that: unlike static functions that can be called on their own, the call of a member function requires knowledge of two things - the function being called, and the object on which to call it. That is why it is not possible to pass a member function to an API expecting a "plain" function pointer.

    If you do not have access to the source of the foo class, you can create a static function that calls a member function on an object stored at a well-known location (i.e. in a static variable). If you do, consider changing the API to take a function object, similar to what functions from the standard C++ library do.

    Finally, there is a common approach used in C libraries that take function pointers - passing an additional void* pointer, which will be passed back in a call to your function pointer; pthreads library does that. If this is the case, you can create a struct that wraps the invocation target object, and pass a pointer to this struct to be passed back to your static function.