更新时间:2021-09-21 05:28:18
您不能在PostMessage中传递字符串的地址,因为该字符串在堆栈上可能是线程本地的。当另一个线程拾起它时,它可能已被销毁。
相反,您应该通过new创建一个新的字符串或异常对象,并将其地址传递给另一个线程(通过PostMessage中的WPARAM或LPARAM参数)。然后,另一个线程拥有该对象并负责销毁它。
以下是一些示例代码,说明了如何实现这一点:
try
{
// do stuff
}
catch (const MyException& the_exception)
{
PostMessage(myhWnd, CWM_SOME_ERROR, 0, new std::string(the_exception.error_string));
}
LPARAM CMyDlg::SomeError(WPARAM, LPARAM lParam)
{
// Wrap in a unique_ptr so it is automatically destroyed.
std::unique_ptr<std::string> msg = reinterpret_cast<std::string*>(lParam);
// Do stuff with message
return 0;
}