CString->char* 형변환
| IOCP – 윈속 프로그래밍 IOCP(Input Output Completion Port) 사용 방법 CString 의 형변환 CString to const char * LPSTR, LPCSTR, LPTSTR, LPCTSTR , LPWSTR, LPCWSTR 분석 CString->char* 형변환 |
LPSTR은 char * 형입니다. 해보면 알겠지만 char *형을 CString 형에다
넣으면 들어갑니다. 그러나 반대로는 에러가 납니다.
1.이경우에는 에러가 없습니다.
char a[100] = {"하하"};
CString b = a;
2.이경우에는 에러가 납니다.
CString b = "하하";
char a[100];
a = b;
문제 해결방법은 여러가지가 있겠지만,
CString b ="하하";
char a[100];
strcpy(a,b);
이렇게 strcpy를 써서 char* 형인 a변수로 "하하"를 옮긴다음에 a를 인자로 넘겨주면
에러가 없을것입니다. a가 char* 형이기 때문에 (char* -> char*)당연히 에러가없죠.
CString => char* 변환
char * ch;
CString *str;
1) ch = (LPSTR)(LPCSTR)str;
2) ch = str.GetBuffer(str.GetLength());
3) wsprintf( ch, "%s", str);
char* => CString 변환
1) str = (LPCSTR)(LPSTR)ch;
2) str = ch;
참고)
LPSTR 은 char* 입니다.
LPSTR : char stirng의 32비트 포인터, char* 와 같다.
LPCTSTR : Constant character String의 32비트 포인터
UINT : 32비트 unsigned형 정수
DWORD : unsigned long int형
BYTE : 8비트 unsigned 정수
1.CString 클래스의 GetBuffer()는 CString을 char *로 바꿔줍니다.
ex) CString strTemp = _T("test");
char *getTemp=NULL;
getTemp = malloc(strTemp.GetLength()+1);
strcpy(getTemp, strTemp.GetBuffer(strTemp.GetLength());
printf("결과:%sn", getTemp);
free(getTemp);
2. operator LPCTSTR ()도 마찬가지입니다.
ex) CString strTemp = _T("test");
char *getTemp = (LPSTR)(LPCSTR)strData;
int i=atoi(msg.type);
error C2664: 'atoi' : cannot convert parameter 1 from 'class CString' to 'const char *'
what should I do?
In this case, you don't need to convert if you use the UNICODE version of atoi, _wtoi. Even better is to use _ttoi, which is the TCHAR version and will work for both UNICODE and MBCS: If UNICODE is defined, it will accept a const wchar_t*, if not, a const char*. You don't even need the explicit cast to LPCTSTR, as it will be invoked automatically:
And please don't listen to people who tell you to use CString::GetBuffer() in this situation, they don't know what they are talking about. GetBuffer() is used exclusively to gain write access to CString's internal buffer, not to convert from CString to char*. And if you don't be careful to match every GetBuffer() call with ReleaseBuffer(), using that CString object will produce unpredictable results.
[]