Using wxWidgets with custom main function

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
Post Reply
DaviFN
In need of some credit
In need of some credit
Posts: 2
Joined: Tue May 12, 2020 7:40 pm

Using wxWidgets with custom main function

Post by DaviFN » Tue May 12, 2020 7:55 pm

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!

catalin
Moderator
Moderator
Posts: 1565
Joined: Wed Nov 12, 2008 7:23 am
Location: Romania

Re: Using wxWidgets with custom main function

Post by catalin » Tue May 12, 2020 11:09 pm

You probably just need the call to

Code: Select all

    wxApp::SetInstance(pApp);

DaviFN
In need of some credit
In need of some credit
Posts: 2
Joined: Tue May 12, 2020 7:40 pm

Re: Using wxWidgets with custom main function

Post by DaviFN » Wed May 13, 2020 1:02 am

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)...

ONEEYEMAN
Part Of The Furniture
Part Of The Furniture
Posts: 4058
Joined: Sat Apr 16, 2005 7:22 am
Location: USA, Ukraine

Re: Using wxWidgets with custom main function

Post by ONEEYEMAN » Wed May 13, 2020 4:18 pm

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.

Post Reply