问题
What is equivalent of the C# string conversion code (between code pages):
public static string Convert(string s)
{
Encoding encoder = Encoding.GetEncoding(858);
return Encoding.Default.GetString(encoder.GetBytes(s));
}
in VC++ (not CLR), e.g. using WideCharToMultiByte/MultiByteToWideChar WinAPI functions?
回答1:
Yes, MultiByteToWideChar()
and WideCharToMultiByte()
are the equivalent Win32 functions, for example:
std::wstring Convert(const std::wstring &s)
{
if (s.empty())
return std::wstring();
int len = WideCharToMultiByte(858, 0, s.c_str(), s.length(), NULL, 0, NULL, NULL);
if (len == 0)
throw std::runtime_error("WideCharToMultiByte() failed");
std::vector<char> bytes(len);
len = WideCharToMultiByte(858, 0, s.c_str(), s.length(), &bytes[0], len, NULL, NULL);
if (len == 0)
throw std::runtime_error("WideCharToMultiByte() failed");
len = MultiByteToWideChar(CP_ACP, 0, &bytes[0], bytes.size(), NULL, 0);
if (len == 0)
throw std::runtime_error("MultiByteToWideChar() failed");
std::wstring result;
result.resize(len);
len = MultiByteToWideChar(CP_ACP, 0, &bytes[0], bytes.size(), &result[0], len);
if (len == 0)
throw std::runtime_error("MultiByteToWideChar() failed");
return result;
}
来源:https://stackoverflow.com/questions/25274797/converting-code-pages-in-c