宽字节wchar_t和窄字节char的相互转换

如下:

PS:如下两个转换函数是参考自windows自带的函数,然后把它封装成了函数的形式,使用时需要注意的一点是每次使用结束之后需要加上

例如:delete[] p;其中p是你函数返回的指针

这是因为在函数内部申请了内存,每次使用完函数之后,函数返回的是一个指针,申请的空间还在,如果不释放内存的话会造成内存泄露,建议最好释放一下。

 1 //将单字节char*转化为宽字节wchar_t*  
 2 wchar_t* AnsiToUnicode( const char* szStr )  
 3 {  
 4     int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0 );  
 5     if (nLen == 0)  
 6     {  
 7         return NULL;  
 8     }  
 9     wchar_t* pResult = new wchar_t[nLen];  
10     MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen );  
11     return pResult;  
12 }  
13   
14 //将宽字节wchar_t*转化为单字节char*  
15char* UnicodeToAnsi( const wchar_t* szStr )  
16 {  
17     int nLen = WideCharToMultiByte( CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL );  
18     if (nLen == 0)  
19     {  
20         return NULL;  
21     }  
22     char* pResult = new char[nLen];  
23     WideCharToMultiByte( CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL );  
24     return pResult;  
25 } 

 

posted @ 2017-10-30 15:34  冥天笑  阅读(545)  评论(0编辑  收藏  举报