variables in a static function

Started by
2 comments, last by Odoacer 19 years, 8 months ago
Okay, so I've been using this little Windows wrapper for my games for a while now, it does everything I need. But now I'm trying to extend it, and I'm running into problems. All my callback functions are static (which I assume is the way it's supposed to be). But the problem is that in my main message processor, I'm trying to call a dialog box. For this I need the handle to the current instance (hInst). Problem is, my current instance isn't static and thus I can't access it. If I add the "static" keyword to it, MSVC throws me a bunch of "unresolved external symbol" errors. How do I fix this? (and why is coding for Windows using classes such a pain?)
Advertisement
Use GetModuleHandle(0)
Callback functions often have a DWORD or LPVOID parameter associated with them. In these cases, I usually pass a pointer to the object (this) to the callback function. Like with CreateThread, I have two functions, one that is static, and is of the DWORD WINAPI ThreadProc_Static(LPVOID lpParameter) form, and the other that is a member function of the form DWORD ThreadProc() form. In the static function, I simply cast the lpParameter argument to the appropriate class pointer type, and call the member ThreadProc() function. So I basically get a callback function that ends up being a member function.
class CClass{  public:    CClass() : mhStop(false), mhThread(NULL)    {      mhThread = CreateThread(NULL, 0, CClass::ThreadProc_Static,  (LPVOID)this, 0, NULL);    }    ~CClass()    {      mStop = true;      if (WaitForSingleObject(mhThread, 1000) == WAIT_TIMEOUT)        TerminateThread(mhThread, -1);      CloseHandle(mhThread);    }  private:    HANDLE mhThread;    bool mhStop;    static DWORD WINAPI ThreadProc_Static(LPVOID lpParameter)    {      return reinterpret_cast<CClass*>(lpParamter)->ThreadProc();    }    DWORD ThreadProc()    {      while (!mhStop)      {        Sleep(100);      }      return 0;    }};
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
Thanks O_o, your solution worked.

Agony, yours looks a lot more flexible though, I'll be sure to keep it around for future reference. One question though, I thought callback functions were supposed to have four parameters? (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)?

Thanks for the help guys!

This topic is closed to new replies.

Advertisement