I'm writing a C++ program which should continuously write to a text file inside an OnIdle event loop (BTW, I'm using wxWidgets -3.0.3 and Visual Studio 17). For this purpose, I'm creating a TextOutputStream as described in the code below inside GetData().
Here gui_magsens->GetFilePath() simply gets a file path from a wxFilePickerCtrl and ActivateDataLoop(true) triggers the OnIdle loop. Now, what I would like to have is a global reference to my tos so that I can use it inside the OnIdle loop without having to create it (and close it) every iteration(not efficient and leads me to unhandled exceptions). What is the best (or cleanest) way to achieve this? What I have found so far is that you could use a pointer to the stream (as shown below), which compiles fine, but throws me a "read access violation" exception(apparently expected as the pointer points to an already "dead" stream). Also, is there a neat workaround without using pointers?
//----main.h----//
//...bunch of variables and functions
wxFileOutputStream* pFos;
wxTextOutputStream* pTos;
//---main.cpp----//
void wxMagSens::GetData()
{
//create stream
wxString f_path = gui_magsens->GetFilePath();
wxFileOutputStream fos(f_path);
wxTextOutputStream tos(fos, wxEOL_NATIVE, wxConvUTF8);
//ptrs
pFos = &fos;
pTos = &tos;
ActivateDataLoop(true);
}
void wxMagSens::OnIdleDataLoop(wxIdleEvent & evt)
{
//write to file
pTos->WriteDouble(some_double);//Here's the exception
//etc...
}
int wxMagSens::OnExit()
{
//USBInterface.USBClose();
if(pFos->IsOk()){ pFos->Close();}
return 0;
}