LPWSTR与char*相互转换

编程入门 行业动态 更新时间:2024-10-26 20:33:35

<a href=https://www.elefans.com/category/jswz/34/1572390.html style=LPWSTR与char*相互转换"/>

LPWSTR与char*相互转换

1.LPWSTR转char*

直接用(char*)强制转换虽然不报错,但是数据会出错,使用以下代码可以完成LPWSTR对char*的无损转换 

/******************************************************************************************
Function:        ConvertLPWSTRToLPSTR
Description:     LPWSTR转char*
Input:           lpwszStrIn:待转化的LPWSTR类型
Return:          转化后的char*类型
*******************************************************************************************/
char* ConvertLPWSTRToLPSTR(LPWSTR lpwszStrIn)
{LPSTR pszOut = NULL;try{if (lpwszStrIn != NULL){int nInputStrLen = wcslen(lpwszStrIn);// Double NULL Termination  int nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;pszOut = new char[nOutputStrLen];if (pszOut){memset(pszOut, 0x00, nOutputStrLen);WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);}}}catch (std::exception e){}return pszOut;
}

2.char* 转换成 LPCTSTR

 

char ch[1024] = "wo shi ni baba";
int num = MultiByteToWideChar(0,0,ch,-1,NULL,0);
wchar_t *wide = new wchar_t[num];
MultiByteToWideChar(0,0,ch,-1,wide,num);

num 获得长字节所需的空间

MultiByteToWideChar()表示将s中的字符传递到ps指向的内存中。-1表示传输至s中的'\0'处,num表示传递的字节个数。

3.LPWSTR转char*

wchar_t widestr[1024] = L"wo shi ni yeye";
int num = WideCharToMultiByte(CP_OEMCP,NULL,widestr,-1,NULL,0,NULL,FALSE);
char *pchar = new char[num];
WideCharToMultiByte (CP_OEMCP,NULL,widestr,-1,pchar,num,NULL,FALSE);

更多推荐

LPWSTR与char*相互转换

本文发布于:2024-02-24 18:39:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1696298.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:LPWSTR   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!