理解AfxGetMainWnd

昨天在尝试用vs2003编译vc6的程序时碰到个问题,对话框应用程序,主对话框提供如下的Get方法:
long CMainDlg::GetHandle(int nChannel)
{
if (IsValidChannel(nChannel))
return m_lHandle[nChannel];
else
return -1;
}
inline BOOL CServerDlg::IsValidChannel(int nChannel)
{
return ((nChannel > -1) && (nChannel < m_nChannelSum));
}
其中m_lHandle和m_nChannelSum均为主对话框的private成员
主对话框启动了一个工作线程,线程中需调用上述的GetHandle
方法1.
CMainDlg* pDlg = (CMainDlg *)AfxGetMainWnd();
pDlg->GetHandle(nChannel);
vc6 ok
vc7 crash,在调用到IsValidChannel的时候报Access violation,应该是不能访问m_nChannelSum
方法2.
CMainDlg* pDlg = reinterpret_cast<CMainDlg *>pParam;
pDlg->GetHandle(nChannel);
vc6&vc7均ok
刚开始一直错以为是reinterpret_cast的奥妙,原来是AfxGetMainWnd的问题。
MSDN中的说明:

If your application is an OLE server, call this function to retrieve a pointer to the active main window of the application instead of directly referring to the m_pMainWnd member of the application object.

If your application is not an OLE server, then calling this function is equivalent to directly referring to the m_pMainWnd member of your application object.

至于是不是OLE server,看C***App::InitInstance中有没有调用AfxEnableControlContainer()

This entry was posted in 软件开发 and tagged , , . Bookmark the permalink.

1 条 理解AfxGetMainWnd 的回复

  1. seon说道:

    原来是不懂多线程

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s