[转载] 转换CString到其它c-string类型
CString
字符串转换成char-array(又叫做c-string)有很多方法,在这里做一下归纳。
ANSI项目
CString
转换到const char*
CString cs("MfcTips.com"); const char* psz = cs.GetString();
CString
转换到char*
CString cs("MfcTips.com"); char* psz = cs.GetBuffer(256); // do something with psz here cs.ReleaseBuffer();
CString
转换到const wchar*
CString csa("MfcTips.com"); CStringW csw(csa); // use an intermediate CStringW const wchar* psz = csw.GetString();
CString
转换到wchar*
CString csa("tinyant.com"); CStringW csw(csa ); // use an intermediate CStringW wchar* psz = csw.GetBuffer(256); // do something with psz here csw.ReleaseBuffer();
CString
转换到std::wstring
CString cs("MfcTips.com"); std::wstring wstr; wstr = CStringW(cs).GetString(); // use an intermediate CStringW
CString
转换到std::string
CString cs("MfcTips.com"); std::string str; str = ws.GetString();
Unicode项目
CString
转换到const wchar*
CString cs(L"MfcTips.com"); const wchar* psz = cs.GetString();
CString
转换到wchar*
CString cs(L"MfcTips.com") wchar* psz = cs.GetBuffer(256); // do something with psz here cs.ReleaseBuffer();
CString
转换到const char*
CString csw(L"MfcTips.com"); CStringA csa(csw); // use an intermediate CStringA const char* psz = csa.GetString();
CString
转换到char*
CString csw(L"MfcTips.com"); CStringA csa(csw); // use an intermediate CStringA char* psz = csa.GetBuffer(256); // do something with psz here csa.ReleaseBuffer();
CString
转换到std::wstring
CString cs(L"MfcTips.com"); std::wstring wstr; wstr = cs.GetString();
CString
转换到std::string
CString cs(L"MfcTips.com"); std::string str; str = CStringA(cs).GetString(); // use an intermediate CStringA
警告:
- Using (LPSTR)(LPCSTR), or (LPTSTR)(LPCTSTR), or (LPWSTR)(LPCWSTR) cast on a CString object to get non-const PSTR is unsafe. It is stupid idiotic nonsense.
- The double cast is handled from right to left so the (LPCSTR) or (LPCTSTR) or (LPCWSTR) is handled first. This will give you a const pointer to the CString object's internal buffer.
- The CString object's internal buffer is "locked" when you access it this way.
- The (LPSTR) or (LPTSTR) or (LPWSTR) cast is handled next. This simply removes the const-ness attribute from the pointer. It does not change anything about the CString object's internal buffer which is what the pointer points to. The CString object's internal buffer is still "locked" when you access it this way.
- So the resulting (non-const) PSTR points to data which is pseudo-const, which could be a very bad thing.
- It compiles, and executes, but if you attempt to modify the data in this PSTR your application may crash.
- If you want to get a non-const PSTR to a CString object's internal buffer, you should use CString::GetBuffer(Size).