将 C++ 成员函数赋值给 C 函数指针

2021-12-24 00:00:00 pointers c c++ boost

我有一个带有如下结构的 C 库:

I have a C library with a struct like this:

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

现在,我有一个类

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

这是行不通的,因为 print 是一个成员函数,必须在 B 的对象上调用.因此我尝试使用 boost::bind 函数:

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)

这也不起作用.

我还尝试修改 C 库并将函数指针定义替换为 boost::function 定义.但是随后编译器抱怨没有找到包含在boost/function.h"中的".

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?

推荐答案

您根本无法做到这一点.成员函数有一个隐式的 this 参数,它是一个指向调用函数的对象的指针.不将 B* 作为参数的函数将永远无法在特定的 B 实例上运行,并且不将这一点作为其第一个参数的函数永远不会与类方法具有相同的签名.有关此问题的更多详细信息和解决方法示例,请阅读:

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.

纯 C++ 项目可以使用 std::function &std::bind 来实现您的要求,但 C++ 项目使用的 C 库无法使用这些类型.

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.

相关文章