Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c++ - Class method as winAPI callback

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 :).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 << '
';
  }
  static void callback_(int blah, void* user_data)
  {
    my_class* that = static_cast<my_class*>(user_data);
    that->callback(blah);
  }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...