| re: Conversion from/to String* to/from std::string
Wild Wind wrote:[color=blue]
>
> Hello,
>
> I have the following methods I've written to convert
> from String* to std::string and back:
>
> static void ConvertFromStdString(std::string& inStr,
> System:String* outStr)
> {
> outStr = new String(inStr.c_str());
> }
>
> static void ConvertToStdString(System::String* inStr,
> std::string& outStr)
> {
> int len = inStr->Length();
> char* charStr = __nogc new char[len + 1];
> for (int i = 0; i < len; i++)
> {
> charStr[i] = (char)inStr->Chars[i];
> }
> charStr[len] = '\0';
> outStr = charStr;
> }
>
> Can anyone tell me if there might be some hidden errors
> in these functions (perhaps due to a mixing of managed
> and unmanaged variables)?[/color]
The second fn will be pretty slow w/ the loop, and the cast to char is a
potential for somewhat undefined behavior for UNICODE characters (specifically,
chars above 8 bits).
You should take a look into Marshal::StringToHGlobalAnsi (and its counterpart
Marshal::FreeHGlobal) to get a copy of the string in one call, and assign that
to std::string. |