简体   繁体   English

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

[英]Assign C++ member function to C function pointer

I have a C library with a struct like this:我有一个带有如下结构的 C 库:

   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:这是行不通的,因为 print 是一个成员函数并且必须在 B 的对象上调用。因此我尝试使用 boost::bind 函数:

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.我还尝试修改 C 库并将函数指针定义替换为 boost::function 定义。 But then the compiler complains about not finding "" which is included in "boost/function.h".但是随后编译器抱怨没有找到包含在“boost/function.h”中的“”。

Is there a (easy/boost) way of assigning a member function to the struct's pointer?是否有(简单/提升)将成员函数分配给结构指针的方法?

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.成员函数有一个隐式的 this 参数,它是一个指向调用函数的对象的指针。 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.不将 B* 作为参数的函数将永远无法在特定的 B 实例上运行,而不将此点作为其第一个参数的函数永远不会与类方法具有相同的签名。 For more details on this problem and an example of a workaround read:有关此问题的更多详细信息和解决方法示例,请阅读:

https://isocpp.org/wiki/faq/pointers-to-members#memfnptr-vs-fnptr 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.纯 C++ 项目可以使用 std::function 和 std::bind 来实现您的要求,但是 C++ 项目使用的 C 库不能使用这些类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM