Originally Posted by
joaquim
i did:
Code:
const size_t len = filename.length() + 1;
wchar_t wcstring[len];
swprintf(wcstring, len, L"%s", filename.c_str());
now i can convert string to wchar_t
Do absolutely not do that. The first issue that you are just doing a plain dumb widening of char -> wchar_t. But this is wrong. wchar_t is typically a different character set (often unicode). chars are typically ASCII or UTF-8, both of which cannot just be widened into a wchar_t. That will give you incorrect translation.
You need to do a proper conversion. Seeing as GDI is Windows, I'll give you these functions as a starting point for translating between different character sets (you will need to add an error class for throwing errors or change the code to handle errors):
Code:
std::wstring AToU16(const std::string& From)
{
if (From.empty())
return L"";
auto Len = MultiByteToWideChar(CP_ACP, 0, From.data(), (int)From.size(), nullptr, 0);
if (Len > 0)
{
std::wstring Str(Len, L'\0');
MultiByteToWideChar(CP_ACP, 0, From.data(), (int)From.size(), &Str[0], Len);
return Str;
}
throw stf::Errors::FailedToConvertString();
}
std::string U16ToU8(const std::wstring& From)
{
if (From.empty())
return "";
auto Len = WideCharToMultiByte(CP_UTF8, 0, From.data(), (int)From.size(), nullptr, 0, 0, 0);
if (Len > 0)
{
std::string Str(Len, L'\0');
WideCharToMultiByte(CP_UTF8, 0, From.data(), (int)From.size(), &Str[0], Len, 0, 0);
return Str;
}
throw stf::Errors::FailedToConvertString();
}
std::wstring U8ToU16(const std::string& From)
{
if (From.empty())
return L"";
auto Len = MultiByteToWideChar(CP_UTF8, 0, From.data(), (int)From.size(), nullptr, 0);
if (Len > 0)
{
std::wstring Str(Len, L'\0');
MultiByteToWideChar(CP_UTF8, 0, From.data(), (int)From.size(), &Str[0], Len);
return Str;
}
throw stf::Errors::FailedToConvertString();
}
These functions convert between ASCII, UTF-8 and UTF-16 on Windows. char is typically ASCII on Windows unless you've explicitly converted it into UTF-8, so use AToU16.
Furthermore, do not use swprintf/sprintf. You will run into issues with buffer sizes.