본문 바로가기

c++/MFC

[MFC] string to wstring/wstring to string변환/ CStringA <-> CStringW

반응형
std::wstring NarrowToWide(const std::string& szNarrow)
{
	int size = MultiByteToWideChar(
		CP_ACP,           // code page
		0,    // character-type options
		szNarrow.c_str(), // string to map
		szNarrow.size(),  // number of bytes in string
		NULL,  // wide-character buffer
		0      // size of buffer
		);

	size++;

	WCHAR* pBuf = new WCHAR[size];
	memset(pBuf,0,size*sizeof(WCHAR));

	int size2 = MultiByteToWideChar(
		CP_ACP,           // code page
		0,    // character-type options
		szNarrow.c_str(), // string to map
		szNarrow.size(),  // number of bytes in string
		pBuf,  // wide-character buffer
		size      // size of buffer
		);

	std::wstring szWide;
	if(size2>0)
		szWide = pBuf;

	memset(pBuf,0,size*sizeof(WCHAR));
	delete [] pBuf;
	pBuf = NULL;

	return szWide;
}

std::string WideToNarrow(const std::wstring& szWide)
{
	BOOL bUsedDefaultChar=FALSE;
	int size = WideCharToMultiByte(
		CP_ACP,           // code page
		0,    // character-type options
		szWide.c_str(), // string to map
		szWide.size(),  // number of bytes in string
		NULL,  // character buffer
		0,      // size of buffer
		NULL,
		&bUsedDefaultChar);

	size++;

	CHAR* pBuf = new CHAR[size];
	memset(pBuf,0,size*sizeof(CHAR));

	bUsedDefaultChar=FALSE;
	int size2 = WideCharToMultiByte(
		CP_ACP,           // code page
		0,    // character-type options
		szWide.c_str(), // string to map
		szWide.size(),  // number of bytes in string
		pBuf,  // character buffer
		size,      // size of buffer
		NULL,
		&bUsedDefaultChar);

	std::string szNarrow;
	if(size2>0)
		szNarrow = pBuf;

	memset(pBuf,0,size*sizeof(CHAR));
	delete [] pBuf;
	pBuf = NULL;

	return szNarrow;
}
반응형