[RESOLVED] Unicode string conversion function issue
Hey.
For some reason, wstr ends up being an empty string. I've debugged it and it the conversion functions works, but it seems that when it returns the string something goes wrong:
Code:
LPCWSTR wstr = Conversions::to_wstring("hello").c_str();
Code:
std::wstring Conversions::to_wstring(char* mb_str)
{
const size_t old_size = strlen(mb_str) + 1;
const size_t new_size = old_size * 2;
size_t converted_chars = 0;
boost::scoped_array<wchar_t> wc_string(new wchar_t[new_size]);
mbstowcs_s(&converted_chars, wc_string.get(), old_size, mb_str, _TRUNCATE);
return std::wstring(wc_string.get());
}
std::wstring Conversions::to_wstring(const char* mb_str)
{
return to_wstring(const_cast<char*>(mb_str));
}
Also, what would be a more portable way to determine the size of new_size in Conversions::to_wstring?
Cheers.
Re: Unicode string conversion function issue
You are creating a temporary std::wstring and, using c_str(), assign a pointer to a member of that temporary to the variable wstr. After the assignment, the temporary variable get deleted and you are left with a dangling pointer.
An easy way to avoid this is:
Code:
std::wstring tmp = Conversions::to_wstring("hello");
LPCWSTR wstr = tmp.c_str(); // wstr is valid as long as tmp is in scope
But that still leave the door open for similar bugs. Better to use a std::wstring or CString instead of the LPCWSTR.
Re: Unicode string conversion function issue