-1

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?

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
algorytmus
  • 953
  • 2
  • 9
  • 28

1 Answers1

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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    @MooingDuck: The C# code is NOT converting from codepage 858 to UTF-16. `Encoding.Default` represents the system default codepage (CP_ACP), not codepage 858. The call to `Encoding.Default.GetString()` is interpretting the codepage 858 bytes as if they were encoded in the system codepage. So the C# code is doing the same thing my code is doing, which is why I wrote it the way I did. – Remy Lebeau Aug 13 '14 at 00:54
  • @MooingDuck: what you say would be true only if the C# code were using `encoder.GetString()` instead of `Encoding.Default.GetString()`. – Remy Lebeau Aug 13 '14 at 01:00