This should work on visual studio. This function should never be inline because it allocates temporary variable sized buffer on the stack.
std::string toMultibyte(const wchar_t* src, UINT codepage = CP_ACP)
{
int wcharCount = static_cast<int>(std::wcslen(src));
int buffSize = WideCharToMultiByte(codepage, 0, src, wcharCount, NULL, 0, NULL, NULL);
char* buff = static_cast<char*>(_alloca(buffSize));
WideCharToMultiByte(codepage, 0, src, wcharCount, buff, buffSize, NULL, NULL);
return std::string(buff, buffSize);
}
If your compiler doesn't support _alloca()
, or you have some prejustice against this function, you may use this approach.
template<std::size_t BUFF_SIZE = 0x100>
std::string toMultibyte(const wchar_t* src, UINT codepage = CP_ACP)
{
int wcharCount = static_cast<int>(std::wcslen(src));
int buffSize = WideCharToMultiByte(codepage, 0, src, wcharCount, NULL, 0, NULL, NULL);
if (buffSize <= BUFF_SIZE) {
char buff[BUFF_SIZE];
WideCharToMultiByte(codepage, 0, src, wcharCount, buff, buffSize, NULL, NULL);
return std::string(buff, buffSize);
} else {
auto buff = std::make_unique<char[]>(buffSize);
WideCharToMultiByte(codepage, 0, src, wcharCount, buff.get(), buffSize, NULL, NULL);
return std::string(buff.get(), buffSize);
}
}