各種型別字元之間的轉換(單位元組char*和寬位元組wchar_t*,TCHAR和string的轉換)
阿新 • • 發佈:2019-02-06
- //將單位元組char*轉化為寬位元組wchar_t*
- wchar_t* AnsiToUnicode( constchar* szStr )
- {
- int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0 );
- if (nLen == 0)
- {
- return NULL;
- }
- wchar_t* pResult = newwchar_t[nLen];
-
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen );
- return pResult;
- }
- //將寬位元組wchar_t*轉化為單位元組char*
- inlinechar* UnicodeToAnsi( constwchar_t* szStr )
- {
- int nLen = WideCharToMultiByte( CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL );
- if (nLen == 0)
- {
- return NULL;
- }
- char* pResult = newchar[nLen];
-
WideCharToMultiByte( CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL );
- return pResult;
- }
-
//在unicode環境下將TCHAR 轉換為std::string
- inline std::string TCHAR2STRING(TCHAR* str)
- {
- int nlen=WideCharToMultiByte(CP_ACP,0,str,-1,NULL,0,NULL,NULL);
- char* res=new char[nlen*sizeof(char)];
- WideCharToMultiByte(CP_ACP,0,str,-1,res,0,NULL,NULL);
- return string(res);
- }