如何通过PostMessage发送字符串?

rec*_*rec 16 c++ mfc multithreading postmessage cdialog

在我的应用程序中,我想从另一个线程向对话框发送消息.我想将std :: exception派生类引用传递给对话框.

像这样的东西:

try {
       //do stuff
}
catch (MyException& the_exception) {
    PostMessage(MyhWnd, CWM_SOME_ERROR, 0, 0); //send the_exception or the_exception.error_string() here
}
Run Code Online (Sandbox Code Playgroud)

我想在对话框中收到消息并显示错误 the_exception.error_string()

LPARAM CMyDlg::SomeError(WPARAM, LPARAM)
{
    show_error( ?????
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

std::string the_exception.error_string()我猜,传递使用PostMessage也没关系.

Mic*_*ael 13

你不能在PostMessage中传递字符串的地址,因为字符串可能是堆栈上的线程本地.当另一个线程拾起它时,它可能已被破坏.

相反,您应该通过new创建一个新的字符串或异常对象,并将其地址传递给另一个线程(通过PostMessage中的WPARAM或LPARAM参数.)然后另一个线程拥有该对象并负责销毁它.

以下是一些示例代码,说明了如何完成此操作:

try
{
    //do stuff
}
catch (MyException& the_exception)
{
    PostMessage(MyhWnd, CWM_SOME_ERROR, 0, new string(the_exception.error_string));
}


LPARAM CMyDlg::SomeError(WPARAM, LPARAM lParam)
{
    // Put in shared_ptr so it is automatically destroyed.
    shared_ptr<string> msg = reinterpret_cast<string*>(lParam);

    // Do stuff with message

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 这里存在内存泄漏的潜在风险。例如,由于消息队列已满,“PostMessage”可能会导致错误。或者,目标窗口可能已经被销毁(因此,不会调用“delete”运算符)。您可以建议一些变体,我们如何才能安全地防止内存泄漏? (2认同)