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.
-
dqf88
- Experienced Solver

- Posts: 55
- Joined: Fri Aug 10, 2012 9:59 am
Post
by dqf88 » Wed Feb 04, 2015 11:37 am
How to convert wxString type to char* type ? I dealt with it like this,but don't work,why?
Code: Select all
wxString str="I' m a string!";
char* s=str.mb_str();
-
DavidHart
- Site Admin

- Posts: 4027
- Joined: Thu Jan 12, 2006 6:23 pm
- Location: IoW, UK
Post
by DavidHart » Wed Feb 04, 2015 12:31 pm
Hi,
(I moved this thread, like your last one, from 'General Development' to here as they are both standard C++ issues.' General Development' is for things that don't fit comfortably elsewhere.)
str.mb_str() returns a temporary pointer, which immediately loses scope. See
https://wiki.wxwidgets.org/Converting_e ... to_char.2A for more information.
Regards,
David
-
guzzi_jones
- Experienced Solver

- Posts: 81
- Joined: Sun Dec 08, 2013 3:50 am
Post
by guzzi_jones » Thu Feb 05, 2015 12:42 am
What exactly is a temporary pointer? Is there a link to a tutorial to explain that? * edit* it is an object created on the stack. so it is not created with new and is automatically deleted when it goes out of scope . since char * is also a pointer it is setting it's address to the address returned by mb_str(). Then the memory at that address is deleted.
I am new, but here is what i did on a project of mine:
Code: Select all
string ltype_desc=wx_ltype.mb_str(); //this copies the char * into a string object. the equals has been overloaded to do this.
char * cString=ltype_desc.c_str();// *edit got rid of redundant stringstream
I suppose you could write a class for this to avoid duplicate code.
-
guzzi_jones
- Experienced Solver

- Posts: 81
- Joined: Sun Dec 08, 2013 3:50 am
Post
by guzzi_jones » Thu Feb 05, 2015 2:14 pm
thanks PB.
One clarification, though. I didn't use wxstring.c_str(). I first created a str::string object and then used string.c_str().
I am still learning c++ , (obviously), and really appreciate your feedback.
-
PB
- Part Of The Furniture

- Posts: 2821
- Joined: Sun Jan 03, 2010 5:45 pm
Post
by PB » Thu Feb 05, 2015 7:11 pm
guzzi_jones wrote:One clarification, though. I didn't use wxstring.c_str(). I first created a str::string object and then used string.c_str().
Ah, I'm sorry, I missed that. On the other hand (and I may be wrong again), std::string is not most suitable for storing multibyte (e.g. UTF-8) strings, as many of its operations assume one character = one byte. There is also wchar_t based std::wstring (and few more string types in C++11), which may be more suited for handling Unicode characters.