MFC 编程:编译时出错:线程代码中的错误

MFC programming: error while compiling: error in code of a thread

本文关键字:代码 线程 错误 出错 编程 编译 MFC      更新时间:2023-10-16

我在以下代码中遇到错误。

DWORD WINAPI CMbPoll::testThread(LPVOID lpVoid)
{
    DWORD dwWaitResult; 
    while(1)
    {
        dwWaitResult = WaitForSingleObject(ghSemaphore, INFINITE/*0L*/);
        if (connectionSuccessful == 1)
        {
            staticConnectionStatus.ShowWindow(FALSE);
        }
        else
        {
            staticConnectionStatus.ShowWindow(TRUE);
        }
        MessageBoxW(L"hi");
        switch (dwWaitResult)
        {
            case WAIT_OBJECT_0:
                Read_One_t(pollSlaveId[0], pollAddress[0], 0);
                temporaryCount++;
                break;
            case WAIT_TIMEOUT: 
                temporaryCount++;
                break;
            default:
                break;
        }
    }
}

错误是:
我。
staticConnectionStatus.ShowWindow(FALSE);
错误 C2228:".ShowWindow'必须具有类/结构/联合

第二。
MessageBoxW(L"hi");
错误 C2352:"CWnd::消息框W":非法调用非静态成员函数

我无法理解为什么会出现这些错误。

我对testThread的声明是:

static DWORD WINAPI testThread(LPVOID lpVoid);

staticConnectionStatus 是 MFC 中窗体上静态文本标签的成员变量。

DDX_Control(pDX, IDC_STATIC_CONFIG6, staticConnectionStatus);

提前谢谢你。

这是因为testThread是静态的。静态方法无法访问类的实例变量。

解决方案(最近出现了很多)是使testThread非静态,并使用回调函数启动线程并调用CMbPoll::testThread,使用传递给CreateThreadthis指针。

DWORD WINAPI thread_starter(LPVOID lpVoid)
{
    return ((CMbPoll*)lpVoid)->testThread();
}
CreateThread(..., thread_starter, this, ...);

我假设您从 CMbPoll 方法中的代码启动线程,如果没有,则将 this 替换为CMbPoll对象的地址。