728x90
이 포스트는 이전 블로그에서 이전된 포스트입니다.

 

검색해 보면 다들 멀티바이트의 경우라 현재의 최신버전 visual studio에서는 오류를 출력한다.

 

따라서 최신 컴파일러를 사용해 유니코드 환경이라면 아래 처럼 가능하다.

이는 Cstring -> Char* 로 변형하는 것이다.

 

CString tmpcstr = _T("testing");
char * tmpch;

int sLen = WideCharToMultiByte(CP_ACP, 0, m_strInput, -1, NULL, 0, NULL, NULL);       
tmpch = new char[sLen + 1];
WideCharToMultiByte(CP_ACP, 0, m_strInput, -1, tmpch, sLen, NULL, NULL);

//사용 후, 마지막에 동적할당 된 메모리를 제거해야 합니다.
delete []tmpch;

 

아래는 코드에 대한 설명이다.

참고로 MultiByteToWideChar는 멀티바이트에서 유니코드로 변환하는 함수이고, WideCharToMultiByte는 유니코드에서 멀티바이트로 변환하는 함수이다.

 

int sLen = WideCharToMultiByte(CP_ACP, 0, m_strInput, -1, NULL, 0, NULL, NULL);      

   -> WideCharToMultiByte 함수는 변환할 문자열의 길이를 리턴한다.

tmpch = new char[sLen + 1];

   -> 저장될 문자열 공간을 동적 할당한다.

WideCharToMultiByte(CP_ACP, 0, m_strInput, -1, tmpch, sLen, NULL, NULL);

   -> 아래 순서대로 인자에 대한 설명이다.

    __in UINT     CodePage,       // 변환할 코드 페이지( 기본적으로 CP_ACP 사용)
    __in DWORD    dwFlags,      // 변환 타입을 나타낸다.
    __in_ecount(cchWideChar) LPCWSTR  lpWideCharStr,    // 변환할 문자열
    __in int      cchWideChar,   // 변화할 문자열의 사이즈
    __out_bcount_opt(cbMultiByte) __transfer(lpWideCharStr) LPSTR   lpMultiByteStr,  // 변환값 저장 버퍼
    __in int      cbMultiByte,      // 변환될 값의 사이즈
    __in_opt LPCSTR   lpDefaultChar,
    __out_opt LPBOOL  lpUsedDefaultChar

참고 원문 : http://blog.naver.com/doug0476/10145174622

delete []tmpch;
   -> 동적 메모리 제거
 

 

 
반대로의 작업이다.
이는 char* -> CString 로 변형하는 것이다.
char* ps = "wow";
CString str;

int len = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, ps, -1, NULL, NULL);    
str = new TCHAR[len];
MultiByteToWideChar(CP_ACP, 0, ps, -1, (LPWSTR)(LPCWSTR)str, len);

//Testing
AfxMessageBox(str);
728x90

+ Recent posts