Class method as winAPI callback

c++, winapi

Solution

You cannot use non-`static` member functions for C callbacks.

However, usually C callbacks have a user data pointer that's routed to the callback. This can be explored to do what you want with the help of a `static` member functions:

// Beware, brain-compiled code ahead!

typedef void (*callback)(int blah, void* user_data);

void some_func(callback cb, void* user_data);

class my_class {
public:
  // ...
  void call_some_func()
  {
     some_func(&callback_,this);
  }
private:
  void callback(int blah)
  {
    std::cout << blah << '\n';
  }
  static void callback_(int blah, void* user_data)
  {
    my_class* that = static_cast<my_class*>(user_data);
    that->callback(blah);
  }
};

Problem

Is it feasible to set the winAPI message callback function as a method of a class. If so, how would this be best implemented? I wonder if it is even possible. Sorry for the short question, hopefully you will be able to provide useful responses. Thanks in advance :).

Original source