passing functor as function pointer

Viewed 24797

I'm trying to use a C library in a C++ app and have found my self in the following situation (I know my C, but I'm fairly new to C++). On the C side I have a collection of functions that takes a function pointer as their argument. On the C++ side I have objects with a functor which has the same signature as the function pointer needed by the C function. Is there any way to use the C++ functor as a function pointer to pass to the C function?

11 Answers

With C++11, you can use std::bind to solve the problem

#include <stdio.h>
#include <functional>

class aClass
{
public:
  int i = 5;
  aClass(int i_) : i(i_) {}
  void operator()(int a, int b) {
      i = i + 1;
      printf ("%d + %d = %d  i = %d\n", a, b, a + b + i, i);
  }
};

void test (int a, int b)
{
  printf ("%d - %d = %d\n", a, b, a - b);
}

template <class op>
void function1 (op function)
{
  function (1, 1);
}

int
main (int argc, const char *argv[])
{
  aClass a(1);
  //  function1 (a);  // this is the wrong way of using it

  using namespace std::placeholders;
  std::function<void(int,int)>  callback;
  callback = std::bind(&aClass::operator(), &a, _1, _2);
  
  function1 (callback);
  function1 (callback);

  function1 (test);
  function1 (test);

  return 0;
}
Related