CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2008
    Posts
    49

    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.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    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.

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    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.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  4. #4
    Join Date
    Sep 2008
    Posts
    49

    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
  •  





Click Here to Expand Forum to Full Width

Featured