Codesynth
Codesynth

Reputation: 23

wxWidgets program gives segmentation fault on wxTextCtrl

I am using wxWidgets 3.0 and C++ for developing a program. I want to use POSIX threads for changing value of text entry of my wxWidgets program. But whenever I run the program, I get segmentation fault when thread is started. The thread I wrote allows to change value of wxTextCtrl per 250 milliseconds.

Here is the code:

#include <stdio.h>

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

class MyApp: public wxApp
{
public:
    virtual bool OnInit();
};

class MyFrame: public wxFrame
{
public:
    MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size);
private:
    void OnExit(wxCommandEvent &event);
    wxDECLARE_EVENT_TABLE();
};

wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
    EVT_MENU(wxID_EXIT, MyFrame::OnExit)
wxEND_EVENT_TABLE()

wxIMPLEMENT_APP(MyApp);

wxTextCtrl *text_entry;

bool MyApp::OnInit()
{
    MyFrame *frame = new MyFrame(
        "wxTextCtrl Example",
        wxPoint(50, 50),
        wxSize(460, 320)
    );
    frame->Show(true);
    return true;
}

pthread_t thread;
int thread_sock;

void *text_delay(void *arg)
{
    for(;;) {
        text_entry->SetValue("Text goes here");
        usleep(250 * 1000);
    }
    return 0;
}

void MyFrame::OnExit(wxCommandEvent &event) { Close(true); }

MyFrame::MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size)
    : wxFrame(NULL, wxID_ANY, title, pos, size)
{
    wxMenu *menuFile = new wxMenu;
    menuFile->Append(wxID_EXIT);
    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(menuFile, "&File");
    SetMenuBar(menuBar);

    text_entry = new wxTextCtrl(
        this, wxID_ANY,
        _(""),
        wxPoint(0, 0),
        wxSize(0, 0),
        wxTE_MULTILINE
    );

    if(!pthread_create(&thread, 0, text_delay, (void*)&thread_sock) < 0) {
        puts("Error while creating a thread!");
        Close(true);
    }
}

Sometimes I get 'Gtk-WARNING: Invalid text buffer iterator' error too. I wanted to run POSIX threads to change value of text box every 250 milliseconds.

Upvotes: 1

Views: 102

Answers (0)

Related Questions