我尝试将结构作为参数传递。

全局结构:

struct ThreadParams
 {
  HWND window;
  LIB::ServiceContainer* mrt;
 };

在主线程中:
ThreadParams threadparams;
threadparams.window = (HWND) GetSafeHwnd();
threadparams.mrt = m_rt;

CWinThread* pthread1;
pthread1 = (CWinThread*) AfxBeginThread(Thread1,(LPVOID)&threadparams,THREAD_PRIORITY_NORMAL,0,0,0);

课外:
UINT Thread1(LPVOID lp)
{
 ThreadParams* threadparams = (ThreadParams*) lp;

     HWND hmainWindow = threadparams->window;
 LIB::ServiceContainer* m_rt = threadparams->mrt;

}

尽管它可以很好地编译,但是在运行时出现错误(这是意外错误),并且我猜想我弄乱了指针m_rt。您是否看到任何明显的错误?

最佳答案

ThreadParams threadparams;

请注意,如果它是一个局部变量,并且声明它的函数在创建线程后返回,则该线程引用的对象不再存在,因为该函数返回时,局部变量将被销毁。如果是这种情况,请使用new创建新实例,如下所示:
ThreadParams * pthreadparams = new ThreadParams();

并将其传递给线程,以便即使创建线程的函数返回也将存在。当然,完成后,您必须手动删除它。

关于c++ - 结构作为AfxBeginThread中的参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9789052/

10-11 18:59