2008/07/02

문자형식 변경하기. UNICODE <-> ASCII

Visual Studio 2005 부터는 프로젝트의 기본 설정이 Unicode 기반으로 설정되어 있다.

따라서 문자열 대입시에 신경을 좀 더 써 주어야 한다.

간단하게 UNICODE 를 ASCII 코드로 바꾸는 일은 USES_CONVERSION; 매크로를 활용하면 쉽다.

변경하고자 하는 위치에 USES_CONVERSION; 을 입력하고 입맛에 맛는 매크로 함수를 호출하기만 하면 된다.


    USES_CONVERSION;

// Unicode 를 Ascii 로 변환 하고자 할 경우
W2A(LPWSTR), T2A(LPWSTR)

// Ascii 를 Unicode로 변경하고자 하는경우
A2W(LPSTR), A2T(LPSTR)

// MSDN 의 예제
//Example 1
// Convert LPCWSTR to LPCSTR.
void ExampleFunctionW( LPCWSTR pszW )
{
// Create an instance of CW2A, called pszA,
// and initialize it with pszW.
CW2A pszA( pszW );
// pszA works like an LPCSTR, and can be used thus:
ExampleFunctionA( pszA );
// Note: pszA will become invalid when it goes out of scope.
}

// Example 2
// Use a temporary instance of CW2A.
void ExampleFunctionW( LPCWSTR pszW )
{
// Create a temporary instance of CW2A,
// and initialize it with pszW.
ExampleFunctionA( CW2A( pszW ) );
// Note: the temporary instance becomes invalid
// after the execution of the statement above.
}

// Example 3
// Incorrect use of conversion macros.
void ExampleFunctionW( LPCWSTR pszW )
{
// Create a temporary instance of CW2A,
// save a pointer to it and then delete
// the temportary instance.
LPCSTR pszA = CW2A( pszW );
// The pszA in the following line is an invalid pointer,
// as the instance of CW2A has gone out of scope.
ExampleFunctionA( pszA );
}

아주 간편해서 좋은데 문제점을 안고 있는 방법이다. 왜 그런지는 자세히 파악이 되지 않았지만 위의 매크로 함수들은 메모리 활용면에서 비효율적인 문제가 있다고 한다. 간단하게 사용하는건 무리가 없는데 한번에 많은 수(10000번이상)의 변환에 이용하게되면 문제가 발생하기도 하였다.
실제로 32비트 프로젝트에서 아무런 문제가 발생하지 않았는데 이를 64비트로 변환시에 위의 함수를 사용하는 곳에서 문제가 발생하였다.

그래서 API를 활용하는 방법으로 바꾸어 사용을 하였다.
API를 이용한 문자형식 변경은 다음 두 함수를 이용하는 것이다.

    // Ascii 를 Unicode 로 변환할 경우
int MultiByteToWideChar(
UINT CodePage,
DWORD dwFlags,
LPCSTR lpMultiByteStr,
int cbMultiByte,
LPWSTR lpWideCharStr,
int cchWideChar
);

// Unicode를 Ascii 로 변환할 경우
int WideCharToMultiByte(
UINT CodePage,
DWORD dwFlags,
LPCWSTR lpWideCharStr,
int cchWideChar,
LPSTR lpMultiByteStr,
int cbMultiByte,
LPCSTR lpDefaultChar,
LPBOOL lpUsedDefaultChar
);


사용방법.
 
// Ascii 를 Unicode 로 변환할 경우
char szSource[1024] = "Sample Ascii string";
WCHAR wszBuf[1024];
int nBufSize = 1024;

MultiByteToWideChar( CP_ACP, 0, szSource, -1, wszBuf, nBufSize);


// Unicode를 Ascii 로 변환할 경우
WCHAR wszSource[1024] = _T("Sample Unicode string");
char szDest[1024];
int nBufSize = 1024

WideCharToMultiByte( CP_ACP, 0, wszSource, -1, szDest, nBufSize,
NULL, NULL );


MSDN - ATL and MFC String Conversion Macros
MSDN - MultiByteToWideChar
MSDN - WideCharToMultiByte
Original Post :
http://neodreamer-dev.tistory.com/119

No comments :

Post a Comment