开发者

Calling a c++ virtual function from WndProc fails

I'm developing a program that displays graphical windows using the windows API. Below is function I provided as the WndProc when registering the window class - it is a static function inside the class WindowsWindow.

#define BTK_DLL_FUNC __dllspec(dllexport)

class AbstractBackend
{
protected:
  bool FatalWarnings;

public:
  AbstractBackend (bool FatalWarnings=false);
  ~AbstractBackend ();

  virtual void StartMainLoop () = 0;
  virtual void QuitMainLoop () = 0;
};

class WindowsBackend : public Base::AbstractBackend
{
public:
  static HINSTANCE hinstance;
  static WindowsBackend* instance;

public:
  BTK_DLL_FUNC WindowsBackend ();
  BTK_DLL_FUNC ~WindowsBackend ();

  BTK_DLL_FUNC void StartMainLoop ();
  BTK_DLL_FUNC void QuitMainLoop ();
};


void WindowsBackend::StartMainLoop ()
{
  MSG Msg;
  while (GetMessage (&Msg, NULL, 0, 0) > 0)
  开发者_Go百科{
    TranslateMessage (&Msg);
    DispatchMessage (&Msg);
  }
}

void WindowsBackend::QuitMainLoop ()
{
  PostQuitMessage (0); /* Send a WM_QUIT message, to stop the main loop */
}

LRESULT CALLBACK WindowsWindow::WndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
  switch (msg)
  {
  case WM_CREATE:
    break;

  case WM_CLOSE:
    DestroyWindow (hwnd);
    break;

  case WM_DESTROY: /* The window was destroyed */
    {
      WindowsBackend::instance->QuitMainLoop (); /* This doesn't work! */
      break;
    }

  default:
    return DefWindowProc(hwnd, msg, wParam, lParam);
  }
  return 0;
}

Now, here is the part I don't understand - The QuitMainLoop doesn't begin and it doesn't return (I tried the debugger and it showed that the Quit function isn't being called, and also that any line after that call isn't being executed). So practically, my program gets stuck after that call.

But, replacing the call to the custom quit function with a direct call to PostQuitMessage works.

Any explanations and/or way to get around this (and be able to call a virtual function) would be highly appriciated.

Edit: Added the exact code


Since you have not posted full code that we can run to reproduce the problem we have to guess.

The only way that I can see for the call to QuitMainLoop() to fail is if WindowsBackend::instance is somehow corrupted. Have you destroyed it by mistake before calling QuitMainLoop()? Has there been a memory corruption perhaps?

I would look at this under the disassembly view in the debugger. That should tell you what has gone wrong and then you need to follow the clues to find out why.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜