Assign C++ member function to C function pointer

2019-02-20 20:51发布

问题:

I have a C library with a struct like this:

   struct A {
      void process(){
        doProcess();
      };
      void (*doProcess)(void);
   }

Now, I have a class like

class B
{
  public: 
    B(): a(){
      a.doProcess = print();
    }
  void print(){
    // do anything
  }
  private:
    A a;
}

This cannot work since print is a member function and has to be called on an object of B. Thus I tried to use the boost::bind function:

a.doProcess = boost::bind(&A::print, this)

This does not work either.

I also tried to modify the C Library and replace the function pointer definition with a boost::function definition. But then the compiler complains about not finding "" which is included in "boost/function.h".

Is there a (easy/boost) way of assigning a member function to the struct's pointer?

回答1:

You simply cannot do this. Member functions have an implicit this argument that is a pointer to the object on which the function is being called. A function that does not take a B* as an argument will never manage to run on a specific B instance and a function that does not take this point as its first argument can never have the same signature as a class method. For more details on this problem and an example of a workaround read:

https://isocpp.org/wiki/faq/pointers-to-members#memfnptr-vs-fnptr

Pay attention to the note at the bottom of the answer on how static member functions can be used in such manner.

Pure C++ projects can use std::function & std::bind to achieve what you are asking about, but a C library used by a C++ project cannot work with these types.