Conversion from/to String* to/from std::string

W

Wild Wind

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 = (char)inStr->Chars;
}
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)?

TIA,
 
J

Julie

Wild said:
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 = (char)inStr->Chars;
}
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)?


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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top