C++中char*转换为LPCWSTR的解决方案

[转载]更新时间:2017年01月04日 10:49:32 原作者:周旭光

最近在学习C++,遇到了一个char转换为LPCWSTR的问题,通过查找资料终于解决了,所以下面这篇文章主要介绍了C++中char转LPCWSTR的解决方案,文中通过详细的示例代码介绍的很详细,有需要的朋友可以参考借鉴,下面来一起看看吧。

前言
大家在学习或者使用Windows编程中,经常会碰到字符串之间的转换,char*转LPCWSTR也是其中一个比较常见的转换。下面就列出几种比较常用的转换方法。大家可以根据自己的需求选择相对应的方法,下面来一起学习学习吧。

1、通过MultiByteToWideChar函数转换

MultiByteToWideChar函数是将多字节转换为宽字节的一个API函数,它的原型如下:

// int MultiByteToWideChar( 
 UINT CodePage,   // code page 
 DWORD dwFlags,   // character-type options 
 LPCSTR lpMultiByteStr, // string to map 
 int cbMultiByte,  // number of bytes in string 
 LPWSTR lpWideCharStr, // wide-character buffer 
 int cchWideChar  // size of buffer 
);

LPCWSTR实际上也是CONST WCHAR *类型

char* szStr = "测试字符串"; 
WCHAR wszClassName[256]; 
memset(wszClassName,0,sizeof(wszClassName)); 
MultiByteToWideChar(CP_ACP,0,szStr,strlen(szStr)+1,wszClassName, 
 sizeof(wszClassName)/sizeof(wszClassName[0]));

2、通过T2W转换宏

char* szStr = "测试字符串";  
CString str = CString(szStr); 
USES_CONVERSION; 
LPCWSTR wszClassName = new WCHAR[str.GetLength()+1]; 
wcscpy((LPTSTR)wszClassName,T2W((LPTSTR)str.GetBuffer(NULL))); 
str.ReleaseBuffer();

上述方法都是UniCode环境下测试的。
转自脚本之家
https://www.jb51.net/article/101978.htm

猜你喜欢

转载自blog.csdn.net/weixin_42628147/article/details/86549027