0

I am trying to convert a member function pointer to standard C function pointer without success.

I tried different methods but I miss something.

My problem is that I need to call a library's function that takes as argument a functor:

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

inside a class in this way:

class base_t {

  public:

    void setCallback(){

      setFunction(&_callback);

    }

  private:

    void _callback(float * a, int b, int c, int d, int e) { ... }

};    

Unfortunately, the _callback() function cannot be static.

I'm also tried to use std::bind but without fortune.

Is there any way I can pass the member to the function?

thewoz
  • 499
  • 2
  • 4
  • 23

1 Answers1

2

I am trying to convert a member function pointer to standard C function pointer without success.

Short answer: You cannot.

Longer answer: Create a wrapper function to be used as a C function pointer and call the member function from it. Remember that you will need to have an object to be able make that member function call.

Here's an example:

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);
   }
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270