locked
.Net / standard string conversion RRS feed

  • Question

  • I would like to convert a .Net System::String to a std::string or to a char*
    I've tried ToCharArray() member function but it seems incompatible with standard char (or wchar_t) arrays
    Monday, November 17, 2008 6:12 PM

Answers

  • Express doesn't have these header files.  Use Marshal::StringToHGlobalAnsi().
    Hans Passant.
    • Marked as answer by Agapornis Tuesday, November 18, 2008 2:28 PM
    Tuesday, November 18, 2008 6:22 AM

All replies

  • If you're using VC++ 2008, you can use msclr::interop::marshal_as to do this:

    // given System::String^ str 
     
    // System::String^ to std::string 
    std::string s = msclr::interop::marshal_as<std::string>(str); 
     
    // System::String^ to const char* 
    msclr::interop::marshal_context context; 
    const char* chars = context.marshal_as<const char*>(str); 
    // chars will be unusable when context goes out of scope, so you'll need to use it immediately or copy it somewhere 

    See here for more information on marshal_as and marshal_context.

    If you're not using VC++ 2008, post back and we can recommend some alternative approaches.
    Monday, November 17, 2008 6:29 PM
  • I'm missing marshal.h, is that because I'm using the Express?

    (VC++ 2008)

    • Proposed as answer by Simon Brooke Friday, October 30, 2009 11:00 AM
    Monday, November 17, 2008 11:39 PM
  • I'm not sure, to be honest. If Express doesn't come with the Marshalling library, then that isn't documented on the Edition Comparison page.

    Just to double-check, you're doing '#include <msclr/marshal.h>', not '#include <marshal.h>' correct?
    Tuesday, November 18, 2008 12:14 AM
  • Express doesn't have these header files.  Use Marshal::StringToHGlobalAnsi().
    Hans Passant.
    • Marked as answer by Agapornis Tuesday, November 18, 2008 2:28 PM
    Tuesday, November 18, 2008 6:22 AM
  • It works,
    Thanks!

    PS: I don't have the "msclr" directory at all...
    Tuesday, November 18, 2008 2:32 PM
  • It's worth noting that anything allocated by Marshal::StringToHGlobalAnsi must be deallocated by Marshal::FreeHGlobal. Do not try to delete it, or free() it, and don't forget to deallocate it.
    Tuesday, November 18, 2008 5:17 PM
  • marshal.h is in msclr so you need

    #include <msclr\marshal.h>

    For different conversions you may need one of:

    #include <msclr\marshal_cppstd.h> 
    #include <msclr\marshal_windows.h> 
    #include <msclr\marshal_atl.h> 
    

    I think each of these includes marshal.h but I have not verified this. I have to say I have not made this work and am still struggling, so do not take this as gospel.

    • Edited by Simon Brooke Friday, October 30, 2009 11:20 AM Standard editor made a horrible mess
    Friday, October 30, 2009 11:05 AM