0

I don't know if this is possible to do that. Since one of my function need to pass a function object to c library function and which can only take function pointer.

I created a demo program and I think it is enough to illustrate my purposes:

#include <iostream>
#include <functional>
class Test;

void init_class(std::function<int (int)> fn) {
  int (*new_fn)(int) = nullptr; // I can't assign fn to new_fn either <<<<<<<<<<<<
  new_fn = fn;  // this complains <<<<<<<<<<<<<<<<<<<<<<<<<
  std::cout << new_fn(199) << std::endl;
}

class Test {
 public:
  explicit Test()
      : n_(199) {
  }
  ~Test() noexcept {}

  int calculate(int val) {
    return n_ + val;
  }

  void run() {
    std::function<int (int)> fn =
      std::bind(&Test::calculate, this, std::placeholders::_1);
    init_class(fn);
  }

 private:
  int n_;
};

void test() {
  Test a;
  a.run();
}

int main(int argc, const char *argv[]) {
  test();
  return 0;
}
randomness2077
  • 1,042
  • 2
  • 13
  • 20
  • 1
    It's not possible to do that. You can use the horrible hack of having a plain function that reads a global for any state you want it to have, but that's it. – Jon Jun 21 '14 at 19:34
  • See https://stackoverflow.com/questions/1000663/using-a-c-class-member-function-as-a-c-callback-function/56943930#56943930 – cibercitizen1 Jul 09 '19 at 06:55

1 Answers1

1

I had the same problem - look at the link below, there are few interesting answers:
Convert C++ function pointer to c function pointer
in brief you can't assign a function pointer to a non-static c++ member function. What you can do is to create a static or global function that makes the call with an instance parameter, look at link above for more details.

Community
  • 1
  • 1
RRR
  • 3,421
  • 13
  • 48
  • 68