单双字节字串转换示例:
//单(string)->双字节(CString)字串
void doSomething(string aStr) {
USES_CONVERSION;
LPCTSTR x = A2CT(aStr.c_str());
CString xx = x;
...
}
//双(CString)->单字节(string)字串
void doSomething(CString tStr) {
USES_CONVERSION;
LPCSTR x = T2CA(tStr);
string xx = x;
...
}
编码转换函数:
#define STACK_ARRAY(TYPE, LEN) static_cast(alloca(LEN * sizeof(TYPE)))
inline std::wstring MutiBytesToCodePage(const std::string& str, UINT CodePage) {
int len16 = ::MultiByteToWideChar(CodePage, 0, str.data(), (int)str.length(), NULL, 0);
wchar_t *ws = STACK_ARRAY(wchar_t, len16);
::MultiByteToWideChar(CodePage, 0, str.data(), (int)str.length(), ws, len16);
std::wstring result(ws, len16);
return result;
}
inline std::wstring ToUtf16(const std::string& str) {
return MutiBytesToCodePage(str, CP_UTF8);
}
inline std::wstring ToSystemCodePage(const std::string& str) {
return MutiBytesToCodePage(str, CP_UTF8);
}
inline std::string WstrToCodePage(const std::wstring& wstr, UINT CodePage) {
int len8 = ::WideCharToMultiByte(CodePage, 0, wstr.data(), (int)wstr.length(), NULL, 0, NULL, NULL);
char* ns = STACK_ARRAY(char, len8);
::WideCharToMultiByte(CodePage, 0, wstr.data(), (int)wstr.length(), ns, len8, NULL, NULL);
std::string result(ns, len8);
return result;
}
inline std::string ToUtf8(const std::wstring& wstr) {
return WstrToCodePage(wstr, CP_UTF8);
}
inline std::string ToSystemCodePage(const std::wstring& wstr) {
return WstrToCodePage(wstr, CP_ACP);
}
调用示例:
void doSomething(string aStr) {
wstring x = MutiBytesToCodePage(aStr, CP_UTF8);
CString xx = xx.c_str();
...
}
没有评论 :
发表评论