-
June 28th, 2009, 03:52 AM
#1
[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.
Last edited by Mybowlcut; June 28th, 2009 at 03:58 AM.
-
June 28th, 2009, 06:17 AM
#2
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.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
-
June 28th, 2009, 06:34 AM
#3
Re: Unicode string conversion function issue
Ah, yes! Thanks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|