|
-
October 9th, 2011, 04:20 PM
#1
convert std::string to gchar*?
I am using webkitgtk in order to learn some C++ development skills in a small project.
I am having trouble converting a string to a gchar* in order to allow me to open up an URL.
I have searched the internet for a while and I am unable to find anything which actually works.
Thanks in advance.
-
October 9th, 2011, 07:10 PM
#2
Re: convert std::string to gchar*?
According to this,
http://developer.gnome.org/glib/2.28...pes.html#gchar
gchar is a typedef of the standard char type.
The std::string's c_str() method will return a const char* (and thus equivalently a const gchar*). However, if you need a non-const gchar* this isn't good enough.
For simply opening a URL, I can't imagine why the string would need to be modifiable, but unfortunately not every API enforces const-correctness properly.
One option is to do this:
Code:
string str;
vector<gchar> modifiable(str.c_str(),str.c_str()+str.length()+1);
func_needing_gchar_pointer(&modifiable[0]);
This of course implies making a copy, so it is not optimally efficient. Prefer just using c_str() when you can.
Last edited by Lindley; October 10th, 2011 at 07:38 AM.
-
October 9th, 2011, 11:18 PM
#3
Re: convert std::string to gchar*?
It was not guaranteed until the latest edition of the C++ standard, but now that the contents of a std::string are stored contiguously, you could write:
Code:
string str;
// str would be given some suitable value here, with a terminating null character
// ...
func_needing_gchar_pointer(&str[0]);
Of course, as this requirement is new an older implementation of the standard library might not conform to this.
EDIT:
Then again, if the function is guaranteed not to change the contents of the string (i.e., it is merely not const-correct), then using c_str() with const_cast may be better.
Last edited by laserlight; October 9th, 2011 at 11:20 PM.
-
October 10th, 2011, 03:50 AM
#4
Re: convert std::string to gchar*?
Thanks for the help, I will try this tonight after work when I get home.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|