Hier ist eine plattformübergreifende Version, die ich für ein Framework geschrieben habe, an dem ich gerade arbeite. Es verwendet die UTF8-Codepage, kann sich aber bei Bedarf jederzeit ändern. Dies ist eine abgespeckte Version, da sie nicht alle expliziten Makrodefinitionen enthält, aber Sie können die Idee davon erhalten:
#if defined(OMNI_OS_WIN)
#include <windows.h>
#endif
#include <cctype>
#include <cwctype>
#include <string>
// not sure if these are all needed .. haven't had my midnight coffee :)
std::string omni::string::to_string(const std::wstring& str)
{
size_t sz = str.length();
#if defined(OMNI_OS_WIN)
int nd = WideCharToMultiByte(CP_UTF8, 0, &str[0], sz, NULL, 0, NULL, NULL);
std::string ret(nd, 0);
int w = WideCharToMultiByte(CP_UTF8, 0, &str[0], sz, &ret[0], nd, NULL, NULL);
if (w != sz) {
#if defined(OMNI_THROW_ON_ERR)
throw omni::string_exception("Invalid size written");
#else
OMNI_ERR_RETV("");
#endif
}
return ret;
#else
const wchar_t* p = str.c_str();
char* tp = new char[sz];
size_t w = wcstombs(tp, p, sz);
if (w != sz) {
delete[] tp;
#if defined(OMNI_THROW_ON_ERR)
throw omni::string_exception("Invalid size written");
#else
OMNI_ERR_RETV("");
#endif
}
std::string ret(tp);
delete[] tp;
return ret;
#endif
}
std::wstring omni::string::to_wstring(const std::string& str)
{
#if defined(OMNI_OS_WIN)
size_t sz = str.length();
int nd = MultiByteToWideChar(CP_UTF8, 0, &str[0], sz, NULL, 0);
std::wstring ret(nd, 0);
int w = MultiByteToWideChar(CP_UTF8, 0, &str[0], sz, &ret[0], nd);
if (w != sz) {
#if defined(OMNI_THROW_ON_ERR)
throw omni::string_exception("Invalid size written");
#else
OMNI_ERR_RETV(L"");
#endif
}
return ret;
#else
const char* p = str.c_str();
size_t len = str.length();
size_t sz = len * sizeof(wchar_t);
wchar_t* tp = new wchar_t[sz];
size_t w = mbstowcs(tp, p, sz);
if (w != len) {
delete[] tp;
#if defined(OMNI_THROW_ON_ERR)
throw omni::string_exception("Invalid size written");
#else
OMNI_ERR_RETV(L"");
#endif
}
std::wstring ret(tp);
delete[] tp;
return ret;
#endif
}
Hier ist ein Beispiel dafür:
std::string s = "here's a standard string";
std::wstring w = L"here's a wide string";
std::string sw = omni::string::to_string(w);
std::wstring ws = omni::string::to_wstring(s);
std::cout << "s = " << s << std::endl;
std::wcout << "w = " << w << std::endl;
std::cout << "sw = " << sw << std::endl;
std::wcout << "ws = " << ws << std::endl;
Hoffe das kann jemandem helfen.