Page 1 of 1

Using wxWidgets with custom main function

Posted: Tue May 12, 2020 7:55 pm
by DaviFN
Hi to all!

I'd like to use my own main function instead of wxWidgets' provided one (via the macro).

I searched a bit and came up with the following code so far:

Code: Select all

wxApp* pApp = new MyApp();
wxEntry(argc, argv);
wxEntryCleanup();
Which I can apparently use in any part of the program.

pApp is an instance of MyApp, which extends wxApp and creates a frame (as shown in one of the examples, the simplest one I guess).

This successfully creates the frame (i.e. window), however, when I close it (the frame, via X button), it seems to not deallocate pApp (there is a memory leak). If I try to call delete on it, the whole program crashes. (I can call delete on pApp right after it's allocated, but after the entry stuff it's not possible anymore.

All I want is to be able to create a window, but only when my program (which happens mainly on the console) calls functions to create these windows. Like, I don't want my program to be dependent on wxWidgets.

I am aware wxApp is supposed to represent an app (the whole program), but can wxWidgets be used as I intend? And is it a reliable way to use it?

I am already able to do it, but, as the perfeccionist I am, I want to fix that memory leak, and also know whether the code is correct and I can continue from here.

Thank you!

Re: Using wxWidgets with custom main function

Posted: Tue May 12, 2020 11:09 pm
by catalin
You probably just need the call to

Code: Select all

    wxApp::SetInstance(pApp);

Re: Using wxWidgets with custom main function

Posted: Wed May 13, 2020 1:02 am
by DaviFN
I was using that call as well. In fact, the loop:

Code: Select all

while(1)
{
	wxApp* pApp = new MyApp();
	MyApp::SetInstance(pApp);
	wxEntryStart(argc, argv);
	wxEntryCleanup();
}
Causes the memory usage to grow indefinitely (i.e. a memory leak).

I can't delete the pApp object (if I do so, whole program crashes)...

Re: Using wxWidgets with custom main function

Posted: Wed May 13, 2020 4:18 pm
by ONEEYEMAN
Hi,
You should be using WinMain function and not main, if you are on Windows.
And use main() on other 2.

That's why its easier to just use wxApp and override the appropriate methods.

Thank you.