I am developing a C++ application using a C library. I have to send a pointer to function to the C library.
This is my class:
class MainWindow : pub
@Snps answer is perfect! But as @DXM mentioned it can hold only one callback. I've improved it a little, now it can keep many callbacks of the same type. It's a little bit strange, but works perfect:
#include
template
struct ActualType {
typedef T type;
};
template
struct ActualType {
typedef typename ActualType::type type;
};
template
struct Callback;
template
struct Callback {
typedef Ret (*ret_cb)(Params...);
template
static Ret callback(Args ... args) {
func(args...);
}
static ret_cb getCallback(std::function fn) {
func = fn;
return static_cast(Callback::callback);
}
static std::function func;
};
template
std::function Callback::func;
#define GETCB(ptrtype,callertype) Callback::type,__COUNTER__,callertype>::getCallback
Now you can just do something like this:
typedef void (cb_type)(uint8_t, uint8_t);
class testfunc {
public:
void test(int x) {
std::cout << "in testfunc.test " <