CString ←→ BSTRの変換について
次のコードのように、CString ←→ BSTRの変換を行いたいのですが、データがUTF8だと文字化けしてしまいます。
どうすれば良いでしょうか?
環境:VC++7(.net 2003)+MFC+WinXP
【結果】
CString--------------------------
FFFFFFE2 FFFFFF97 FFFFFF8B 3C
BSTR--------------------------
FFFFFFE2 FFFFFF97 FFFFFF81 45
【ソース】
int intCT;
int nSize = 0;
BYTE *pSource = (BYTE *)"○<";
this->ConvSJistoUtf8(pSource, (BYTE *)NULL, &nSize );
BYTE* pDist = new BYTE[ nSize + 1 ];
ZeroMemory( pDist, nSize + 1 );
this->ConvSJistoUtf8(pSource, pDist, &nSize );
CString str = CString(pDist);
delete []pDist;
pDist = NULL;
BSTR bstr;
bstr=str.AllocSysString();//CString→BSTRへの変換
CString str2=CString(bstr);//BSTR→CStringへの変換
TRACE("CString--------------------------\n ");
for( intCT = 0; intCT < str.GetLength(); intCT++ )
{
if( intCT%16 == 0 ) TRACE("\n");
TRACE("%02X " , str[intCT]);
}
TRACE("\n ");
TRACE("BSTR--------------------------\n ");
for( intCT = 0; intCT < str2.GetLength(); intCT++ )
{
if( intCT%16 == 0 ) TRACE("\n");
TRACE("%02X " , str2[intCT]);
}
TRACE("\n ");
BOOL ConvSJistoUtf8( BYTE* pSource, BYTE* pDist, int* pSize )
{
*pSize = 0;
//ShiftJISからUTF-16へ変換
const int nSize = ::MultiByteToWideChar( CP_ACP, 0, (LPCSTR)pSource, -1, NULL, 0 );
BYTE* buffUtf16 = new BYTE[ nSize * 2 + 2 ];
::MultiByteToWideChar( CP_ACP, 0, (LPCSTR)pSource, -1, (LPWSTR)
buffUtf16, nSize );
//UTF-16からShift-JISへ変換
const int nSizeUtf8 = ::WideCharToMultiByte( CP_UTF8, 0, (LPCWSTR)
buffUtf16, -1, NULL, 0, NULL, NULL );
if( !pDist ){
*pSize = nSizeUtf8;
delete buffUtf16;
return TRUE;
}
BYTE* buffUtf8 = new BYTE[ nSizeUtf8 * 2 ];
ZeroMemory( buffUtf8, nSizeUtf8 * 2 );
::WideCharToMultiByte( CP_UTF8, 0, (LPCWSTR)buffUtf16, -1, (LPSTR)
buffUtf8, nSizeUtf8, NULL, NULL );
*pSize = lstrlen( (char*)buffUtf8 );
memcpy( pDist, buffUtf8, *pSize );
delete buffUtf16;
delete buffUtf8;
return TRUE;
}