Magyar oldal English site

Site map
2024-06-04 17:36:03 (Originally published at: 2012-09-07)

Getting C string form wxString - the correct way

Yesterday I got bitten by the wxWidgets (again). I tryed to get a C string from a wxString using the wxString::mb_str method.

Before continuing reading, read the documentation. What would you expect when you call the method?


My assumption was that if I call the const char * version, it will return the address of some internal buffer, so I can use it as long the particular object is alive.

So I tried this:

    wxString bar = wxT("BAR");
    const char *pStr = bar.mb_str();

But not worked. I even reported a bug: #14633 (wxString::mb_str returns empty string or garbage on 64 bit Ubuntu.) – wxWidgets

After their response I found out only the wxCharBuffer version exists, which can be converted implicitly to const char*. So the returned object is only a temporary. Which is destroyed immediately after the call, so pStr will point to an invalid location immediately.

The solution: immediately copy its contents to a buffer:

    wxString bar = wxT("BAR");
    const char cstr[1000];
    strncpy(cstr, bar.mb_str(), 1000);

This will work. But the documentation says nothing about this. Only their wiki: Converting everything to and from wxString. By the way what is a "temporary pointer"? I only know about temporary objects...

Hope this will help someone!

If you want to discuss this post, share it on social media.
Recently updated:
Logo