俺最近在用VC做项目,其中用到串口操作,调用API函数,要创建一个辅助线程监视串口,对从串口接受到的数据进行操作。(程序是基于对话框的)。当中创建辅助线程时候出现错误。下面我给出部分程序代码,请大家给我建议和指出错误,谢谢大家啦!
UINT CTestDlg::CommThreadProc(LPVOID pParam)//线程函数名
{
//具体的代码实现部分我就不写了,太多了
}
BOOL CTestDlg::StartMonitoring( )//按钮响应事件
{
m_Thread=AfxBeginThread(CommThreadProc,NULL,THREAD_PRIORITY_ABOVE_NORMAL,0,0,NULL);
}
最后编译出现错误: error C2665: 'AfxBeginThread' : none of the 2 overloads can convert parameter 1 from type 'unsigned int (void *)' 小弟我已经调试了多次了,我尝试着把AfxBeginThread函数的第二个参数换成GetSafeHwnd(),各位帮帮忙,我调试了一天不知道错在哪里了????
UINT CTestDlg::CommThreadProc(LPVOID pParam)//线程函数名
{
//具体的代码实现部分我就不写了,太多了
}
BOOL CTestDlg::StartMonitoring( )//按钮响应事件
{
m_Thread=AfxBeginThread(CommThreadProc,NULL,THREAD_PRIORITY_ABOVE_NORMAL,0,0,NULL);
}
最后编译出现错误: error C2665: 'AfxBeginThread' : none of the 2 overloads can convert parameter 1 from type 'unsigned int (void *)' 小弟我已经调试了多次了,我尝试着把AfxBeginThread函数的第二个参数换成GetSafeHwnd(),各位帮帮忙,我调试了一天不知道错在哪里了????
{
//具体的代码实现部分我就不写了,太多了
}
在头文件中定义为static函数或不要定义为成员函数(UINT CommThreadProc(LPVOID pParam))
{
CTestDlg *pTestDlg = (CTestDlg *)pParam;
pTestDlg->InitComPort();
pTestDlg->dosomething();
return 0;
}
BOOL CTestDlg::StartMonitoring( )//按钮响应事件
{
m_Thread=AfxBeginThread(CommThreadProc,this,THREAD_PRIORITY_ABOVE_NORMAL,0,0,NULL); // 加上this;
}或者像楼上所说,把CommThreadProc申明为static;
线程处理函数可以是三种形式:全局的、静态成员函数、普通成员函数。前两种不用说,普通成员函数也是可以的,只是在作为mAfxBeginThread的参数时,要使用一个宏,宏的名字记不清了,可以去查MSDN
在头文件SecondaryThreadDlg.h 声明线程处理函数 UINT WorkerThreadProc( LPVOID Param );
在SecondaryThreadDlg.cpp添加如下代码:
UINT CSecondaryThreadDlg::WorkerThreadProc( LPVOID Param )
{
CFile file;
file.Open("C:\\Temp\\test.txt",CFile::modeCreate|CFile::modeWrite);
CString strValue;
for(int i=0;i<=100;i++)
{
strValue.Format("Value:%d",i);
file.Write(strValue,strValue.GetLength()); // Write to the file for worker thread using AfxBeginThread
}
file.Close();
return TRUE;
}
在按钮事件添加如下代码:
void CSecondaryThreadDlg::OnOK()
{
AfxBeginThread(WorkerThreadProc,NULL,THREAD_PRIORITY_NORMAL,0,0,NULL);
MessageBox("Thread Started");
}
编译时还是出现LZ同样的错误:error C2665: 'AfxBeginThread' : none of the 2 overloads can convert parameter 1 from type 'unsigned int (void *)' 也额肯请各位之处错误在哪里?????
{
static UINT WorkerThreadProc( LPVOID Param );
};
UINT CSecondaryThreadDlg::WorkerThreadProc( LPVOID Param )
{
// 若要用对话框指针,这么还原!!!!
CSecondaryThreadDlg* pDlg = (CSecondaryThreadDlg*)Param; CFile file;
file.Open("C:\\Temp\\test.txt",CFile::modeCreate|CFile::modeWrite);
CString strValue;
for(int i=0;i<=100;i++)
{
strValue.Format("Value:%d",i);
file.Write(strValue,strValue.GetLength()); // Write to the file for worker thread using AfxBeginThread
}
file.Close();
return TRUE;
}
void CSecondaryThreadDlg::OnOK()
{
AfxBeginThread(WorkerThreadProc,this,THREAD_PRIORITY_NORMAL,0,0,NULL);
MessageBox("Thread Started");
}