Assign C++ member function to C function pointer

前端 未结 1 724
失恋的感觉
失恋的感觉 2020-12-11 10:37

I have a C library with a struct like this:

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


        
相关标签:
1条回答
  • 2020-12-11 11:07

    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.

    0 讨论(0)
提交回复
热议问题