(环境:Win7 64位, C++ builder 2010)
C/C++中一般会使用到std::string,但是很少用到std::wstring,一旦使用到就会涉及多字节和宽字节的相互转换。
这里使用到的API为MultiByteToWideChar()和WideCharToMultiByte(),处理时,一般先获取字符长度,然后再根据长度申请内存,最后赋值。示例代码如下:
#include
#include
bool String2WString(const std::string &strSrc, std::wstring &strDest)
{
strDest.clear();
if (strSrc.empty())
{
return true;
}
bool bResult = false;
int iLen = MultiByteToWideChar(CP_ACP, 0, strSrc.c_str(), strSrc.length(), NULL, NULL);
if (iLen == 0)
{
return bResult;
}
wchar_t *pszWBuffer = new wchar_t[iLen + 1];
int iSize = (iLen + 1) * sizeof(wchar_t);
memset(pszWBuffer, 0, iSize);
iLen = MultiByteToWideChar(CP_ACP, 0, strSrc.c_str(), strSrc.length(), pszWBuffer, iSize);
if (iLen != 0)
{
strDest = pszWBuffer;
bResult = true;
}
delete [] pszWBuffer;
pszWBuffer = NULL;
return bResult;
}
bool WString2String(const std::wstring &strSrc, std::string &strDest)
{
strDest.clear();
if (strSrc.empty())
{
return true;
}
bool bResult = false;
int iLen = WideCharToMultiByte(CP_ACP, 0, strSrc.c_str(), strSrc.length(), NULL, 0, NULL, NULL);
if (iLen == 0)
{
return bResult;
}
char *pszBuffer = new char[iLen + 1];
memset(pszBuffer, 0, iLen + 1);
iLen = WideCharToMultiByte(CP_ACP, 0, strSrc.c_str(), strSrc.length(), pszBuffer, iLen + 1, NULL, NULL);
if (iLen != 0)
{
strDest = pszBuffer;
bResult = true;
}
delete pszBuffer;
pszBuffer = NULL;
return bResult;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::string strData("你好 世界");
std::wstring strValue = L"";
String2WString(strData, strValue);
strValue = L"世界 你好";
WString2String(strValue, strData);
system("pause");
return 0;
}