코딩한 서버를 클라이언트와 붙이면서 데이터 형에서 문제를 많이 일으켰다.
첫째, string 을 tchar로 변환
둘째, 멀티바이트 사용 하는 코딩 과 유니코드 사용(내가 코딩한 것) 것 사이의 문제.
TCHAR을 사용한다고 했지만 서버와 클라 사이의 데이터 이동도 많고
결국에는 내 소스 역시 멀티바이트로(클라가 사람이 많으니 다수를 따라서..) 변환 했고
TCHAR로 처리 되었던 것은 string을 char로 변환해서 마무리 했다.
그 과정에서 찾은 데이터 변환 방법 들...
방법 1. 외국 블로그에서
How to convert std::string to TCHAR*
출처 - http://ukanth.in/blog/?p=180
typedef std::basic_string<TCHAR> tstring;
TCHAR* StringToTCHAR(string& s)
{
tstring tstr;
const char* all = s.c_str();
int len = 1 + strlen(all);
wchar_t* t = new wchar_t[len];
if (NULL == t) throw std::bad_alloc();
mbstowcs(t, all, len);
return (TCHAR*)t;
}
std::string TCHARToString(const TCHAR* ptsz)
{
int len = wcslen((wchar_t*)ptsz);
char* psz = new char[2*len + 1];
wcstombs(psz, (wchar_t*)ptsz, 2*len + 1);
std::string s = psz;
delete [] psz;
return s;
}
추가 - mbstowcs 함수 : multi byte char 을 wide char로 변환
wcstombs 는 mbstowcs 의 반대.
사용 예)
// IdSet->getText() 는 string.
tstring tstr;
const char* all = IdSet->getText().c_str();
int len = strlen(all)+1;
wchar_t* t = new wchar_t[len];
if( t == NULL )
throw std::bad_alloc();
mbstowcs( t, all, len );
방법2. String to char*, char* to TCHAR* (유니코드 사용 환경이였으므로 wchar*)
// IdSet->getText() is stl string
// String to char*
char* strID;
size_t tempSize = IdSet->getText().length();
strID = new char[tempSize];
strcpy( strID, IdSet->getText().c_str() );
// char* to TCHAR*
TCHAR szUniID[256] = {0,};
int len = strlen(strID);
::MultiByteToWideChar( CP_ACP, 0, strID, -1, szUniID, len + 1 );
방법 3. string -> const char* -> char* (멀티바이트 사용)
//IdSet->getText() 은 string
char* id;
const char* strID = IdSet->getText().c_str();
id = const_cast<char*>(strID);
// 합쳐서 사용
id = const_cast<char*>( IdSet->getText().c_str() );
추가 - const char*을 char*로 변환
방법 1. 직접 캐스팅
char* str1;
const char* str2;
str1 = (char*)(str2);
방법 2. 형변환 연산자 const_cast 사용
- const 객체에 대한 포인터를 const가 아닌 객체의 포인터로 변환 할때 사용하는 연산자
str1 = const_cast<char*>(str2);
size_t origsize = 0, convertedChars = 0; // 원래 문자열 길이, 변환된 문자열 길이
origsize = strlen(strOriginal.c_str()) + 1; // 변환시킬 문자열의 길이를 구함
mbstowcs_s(&convertedChars, strChange, origsize, strOriginal.c_str(), _TRUNCATE); // 변환
* mbstowcs() 함수를 사용하면 2005 이상의 버젼에서 경고를 띄운다. 그래서 mbstowcs_s() 함수를 사용하고,
mbstowcs_s() 이 함수가 문자열 오버플로우 같은걸 애초에 방지해준다고 검색하다가 본듯
'Windows 개발' 카테고리의 다른 글
기본상식 (0) | 2014.11.21 |
---|---|
unicode 와 ansi, std::string 과 CString 상호 변경하기 (0) | 2014.11.19 |
OutputDebugString 응용 (0) | 2014.11.11 |
tid 구하기 (0) | 2014.10.19 |
dll 분석 (0) | 2014.09.21 |