views:

3207

answers:

3

Can someone please post a simple code that would convert

System::String^

to

C++ std::string

?

i.e I just want to assign the value of

String^ originalString;

to

std::string newString;
+2  A: 

Check out System::Runtime::InteropServices::Marshal::StringToCoTaskMemUni() and its friends.

(Sorry can't post code now; I don't have VS on this machine to check it compiles before posting).

Martin
wow..you remember namespace that long? =p thanks.
ShaChris23
+2  A: 

Here are some conversion routines I wrote many years ago for a c++/cli project, they should still work.

void StringToStlWString ( System::String const^ s, std::wstring& os)
    {
     String^ string = const_cast<String^>(s);
     const wchar_t* chars = reinterpret_cast<const wchar_t*>((Marshal::StringToHGlobalUni(string)).ToPointer());
     os = chars;
     Marshal::FreeHGlobal(IntPtr((void*)chars));

    }
    System::String^ StlWStringToString (std::wstring const& os) {
     String^ str = gcnew String(os.c_str());
     //String^ str = gcnew String("");
     return str;
    }

    System::String^ WPtrToString(wchar_t const* pData, int length) {
     if (length == 0) {
      //use null termination
      length = wcslen(pData);
      if (length == 0) {
       System::String^ ret = "";
       return ret;
      }
     }

     System::IntPtr bfr = System::IntPtr(const_cast<wchar_t*>(pData));
     System::String^ ret = System::Runtime::InteropServices::Marshal::PtrToStringUni(bfr, length);
     return ret;
    }

    void Utf8ToStlWString(char const* pUtfString, std::wstring& stlString) {
     //wchar_t* pString;
     MAKE_WIDEPTR_FROMUTF8(pString, pUtfString);
     stlString = pString;
    }

    void Utf8ToStlWStringN(char const* pUtfString, std::wstring& stlString, ULONG length) {
     //wchar_t* pString;
     MAKE_WIDEPTR_FROMUTF8N(pString, pUtfString, length);
     stlString = pString;
    }
Ben Schwehn
+4  A: 

Don't roll your own, use these handy (and extensible) wrappers provided by Microsoft: http://msdn.microsoft.com/en-us/library/bb384865.aspx

tragomaskhalos