'Calling wxQueueEvent causes segmentation fault

I have just started exploring wxWidgets. I have a main class and a thread that accepts incoming TCP connections. When data is available on the connection I want to post an event for the main thread to handle the data. Here is some code to show what I'm doing.

// My wxFrame class 
class VisorFrame : public wxFrame
{
  public:
    VisorFrame(wxFrame* frame, const wxString& title, const wxPoint& pos, const wxSize& size);
    virtual ~VisorFrame(){};
}

VisorFrame::VisorFrame(wxFrame* frame, const wxString& title, const wxPoint& pos, const wxSize& size) :
    wxFrame(frame, wxID_ANY, title, pos, size)
{
    // create thread to handle TCP connections
    networkThread = new NetworkThread(this->GetEventHandler(), mutexKeepRunning, &keepRunning, mutexCond, cond);
}

This is what I have in my event table:

EVT_THREAD(ID_ProcClientCmd, VisorFrame::OnProcessClientCmd)

// My worker thread class
class NetworkThread : public wxThread
{
    public:
    NetworkThread(wxEvtHandler* parent, wxMutex* mutexKeepRunning, bool* keepRunning, wxMutex* mutexCond, wxCondition* cond);
}

NetworkThread::NetworkThread(wxEvtHandler* parent, wxMutex* mutexKeepRunning, bool* keepRunning, wxMutex* mutexCond, wxCondition* cond)  :
        mutexKeepRunning(mutexKeepRunning), keepRunning(keepRunning), mutexCond(mutexCond), cond(cond)
{
}

// This is how I post my event inside my Thread class:

    if (parent != NULL)
    {
        wxThreadEvent event(wxEVT_THREAD, ID_ProcClientCmd);
        event.SetPayload((void *) pkt_info);
        wxQueueEvent(parent, event.Clone());
    }
    else
        wxPuts(_("NetworkThread: parent is NULL"));

When wxQueueEvent() gets called it throws segmentation fault. I looked at the sampled/thread.cpp code and observed that it calls wxQueueEvent() with a wxFrame pointer. When I try doing the same thing, it won't compile because wxQueueEvent expects a wxEvtHandler* as the first arg.

What am I doing wrong that is causing this seg fault? Thanks for your help



Solution 1:[1]

I think the problem is this part:

    wxThreadEvent event(wxEVT_THREAD, ID_ProcClientCmd);
    event.SetPayload((void *) pkt_info);
    wxQueueEvent(parent, event.Clone());

wxQueueEvent calls wxEvtHandler::QueueEvent() and the documentation for that method states:

this method takes ownership of the event parameter, i.e. it will delete it itself

So you should create the event with the new operator use that pointer like so:

    wxThreadEvent* event = new wxThreadEvent(wxEVT_THREAD, ID_ProcClientCmd);
    event->SetPayload((void *) pkt_info);
    wxQueueEvent(parent, event);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 New Pagodi