這個代碼網上很多,留在這裡做個備份。
static std::string ConvertCStringToUTF8( CString strValue ) { std::wstring wbuffer; wbuffer.assign( strValue.GetString(), strValue.GetLength() ); /* * 轉換ANSI到UNICODE * 獲取轉換後長度 */ int length = ::MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, (LPCTSTR) strValue, -1, NULL, 0 ); wbuffer.resize( length ); /* 轉換 */ MultiByteToWideChar( CP_ACP, 0, (LPCTSTR) strValue, -1, (LPWSTR) (wbuffer.data() ), wbuffer.length() ); /* 獲取轉換後長度 */ int length = WideCharToMultiByte( CP_UTF8, 0, strValue, -1, NULL, 0, NULL, NULL ); /* 獲取轉換後內容 */ std::string buffer; buffer.resize( length ); WideCharToMultiByte( CP_UTF8, 0, strValue, -1, (LPSTR) (buffer.data() ), length, NULL, NULL ); return(buffer); } static CString ConvertUTF8ToCString( std::string utf8str ) { /* 預轉換,得到所需空間的大小 */ int nLen = ::MultiByteToWideChar( CP_UTF8, NULL, utf8str.data(), utf8str.size(), NULL, 0 ); /* 轉換為Unicode*/ std::wstring wbuffer; wbuffer.resize( nLen ); ::MultiByteToWideChar( CP_UTF8, NULL, utf8str.data(), utf8str.size(), (LPWSTR) (wbuffer.data() ), wbuffer.length() ); return(CString( wbuffer.data(), wbuffer.length() ) ); /* * 轉換為ANSI * 得到轉換後長度 */ nLen = WideCharToMultiByte( CP_ACP, 0, wbuffer.data(), wbuffer.length(), NULL, 0, NULL, NULL ); std::string ansistr; ansistr.resize( nLen ); /* 把unicode轉成ansi*/ WideCharToMultiByte( CP_ACP, 0, (LPWSTR) (wbuffer.data() ), wbuffer.length(), (LPSTR) (ansistr.data() ), ansistr.size(), NULL, NULL ); return(CString( ansistr.data(), ansistr.length() ) ); }
文章來源
static std::string ConvertCStringToUTF8( CString strValue ) { std::wstring wbuffer; wbuffer.assign( strValue.GetString(), strValue.GetLength() ); /* * 轉換ANSI到UNICODE * 獲取轉換後長度 */ int length = ::MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, (LPCTSTR) strValue, -1, NULL, 0 ); wbuffer.resize( length ); /* 轉換 */ MultiByteToWideChar( CP_ACP, 0, (LPCTSTR) strValue, -1, (LPWSTR) (wbuffer.data() ), wbuffer.length() ); /* 獲取轉換後長度 */ int length = WideCharToMultiByte( CP_UTF8, 0, strValue, -1, NULL, 0, NULL, NULL ); /* 獲取轉換後內容 */ std::string buffer; buffer.resize( length ); WideCharToMultiByte( CP_UTF8, 0, strValue, -1, (LPSTR) (buffer.data() ), length, NULL, NULL ); return(buffer); } static CString ConvertUTF8ToCString( std::string utf8str ) { /* 預轉換,得到所需空間的大小 */ int nLen = ::MultiByteToWideChar( CP_UTF8, NULL, utf8str.data(), utf8str.size(), NULL, 0 ); /* 轉換為Unicode*/ std::wstring wbuffer; wbuffer.resize( nLen ); ::MultiByteToWideChar( CP_UTF8, NULL, utf8str.data(), utf8str.size(), (LPWSTR) (wbuffer.data() ), wbuffer.length() ); return(CString( wbuffer.data(), wbuffer.length() ) ); /* * 轉換為ANSI * 得到轉換後長度 */ nLen = WideCharToMultiByte( CP_ACP, 0, wbuffer.data(), wbuffer.length(), NULL, 0, NULL, NULL ); std::string ansistr; ansistr.resize( nLen ); /* 把unicode轉成ansi*/ WideCharToMultiByte( CP_ACP, 0, (LPWSTR) (wbuffer.data() ), wbuffer.length(), (LPSTR) (ansistr.data() ), ansistr.size(), NULL, NULL ); return(CString( ansistr.data(), ansistr.length() ) ); }
文章來源
留言
張貼留言