MFC中的CString转char*

2025-01-04 03:21:04
推荐回答(4个)
回答1:

最简单的就是把项目改成多字节字符集,CString就等于const char*,如果需要char*就GetBuffer,用完再ReleaseBuffer或是复制一份.

回答2:

char * cs2ca(CString str)
{
char *ptr;
#ifdef _UNICODE
LONG len;
len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
ptr = new char [len+1];
memset(ptr,0,len + 1);
WideCharToMultiByte(CP_ACP, 0, str, -1, ptr, len + 1, NULL, NULL);
#else
ptr = new char [str.GetAllocLength()+1];
sprintf(ptr,_T("%s"),str);
#endif
return ptr;
}
CString转char*的最佳方案

回答3:

strncpy(tcpPackage.chText, strText.GetBuffer(), 512);
//用完后再调用:
strText.ReleaseBuffer();

回答4:

strcpy(tcpPackage.chText, strText )