将C ++成员函数分配给C函数指针 [英] Assign C++ member function to C function pointer

查看:98
本文介绍了将C ++成员函数分配给C函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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.

这篇关于将C ++成员函数分配给C函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆