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?

1
  • @BoPersson I think this is a good duplicate as well. Commented Feb 7, 2018 at 23:12

1 Answer 1

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);
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Per the question, you will also need "extern "C". As-is, it is not a "standard C function" and its address cannot be passed to a C library.
@BenVoigt, good call. Thanks for the suggestion.
Thanks for the answer. This solution is correct also in case of a multi threads application?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.