使用多个参数将成员功能指针转换为标准C函数

Convert a member function pointer to standard C function with multiple arguments

本文关键字:转换 指针 标准 函数 功能 成员 参数      更新时间:2023-10-16

我正在尝试将成员函数指针转换为标准C功能指针而无需成功。

我尝试了不同的方法,但我想念一些东西。

我的问题是我需要调用库的函数,该函数以参数为函数:

void setFunction(void(*cbfun)(float*,int,int,int,int)){ ... }

以这种方式在课堂内:

class base_t {
  public:
    void setCallback(){
      setFunction(&_callback);
    }
  private:
    void _callback(float * a, int b, int c, int d, int e) { ... }
};    

不幸的是,_callback((函数不能静态。

我也尝试使用std :: bind但没有财富。

有什么办法可以将成员传递到功能?

我正在尝试将成员功能指针转换为标准C功能指针而无需成功。

简短答案:您不能。

更长的答案:创建一个包装函数,以用作C功能指针,并从中调用成员函数。请记住,您将需要一个对象才能使该成员函数调用。

这是一个示例:

void setFunction(void(*cbfun)(float*,int,int,int,int)){ ... }
class base_t;
base_t* current_base_t = nullptr;
extern "C" void callback_wrapper(float * a, int b, int c, int d, int e);
class base_t {
  public:
    void setCallback(){   
       current_base_t = this;
       setFunction(&callback_wrapper);   
    }
  private:
    void _callback(float * a, int b, int c, int d, int e) { ... }
};    
void callback_wrapper(float * a, int b, int c, int d, int e)
{
   if ( current_base_t != nullptr )
   {
      current_base_t->_callback(a, b, c, d, e);
   }
}