char 与 wchar_t的转换,欢迎更正

第一种,使用转换函数:

char* ToChar( wchar_t* buffer )
{
int len = wcslen(buffer);
char* p = NULL;
int need_size = ::WideCharToMultiByte( CP_ACP, 0, buffer, len, p, 0, NULL, NULL );
p = new char[need_size+1];
memset( p, 0, need_size+1 );
ASSERT( ::WideCharToMultiByte( CP_ACP, 0, buffer, len, p, need_size, NULL, NULL ) );
return p;
}


wchar_t* ToWideChar( char* buffer )
{
int len = strlen( buffer);
wchar_t* p = NULL;
int need_size = ::MultiByteToWideChar( CP_ACP, 0, buffer, len, p, 0 );
p = new wchar_t[need_size+1];
wmemset( p, 0, need_size+1 );
ASSERT( ::MultiByteToWideChar( CP_ACP, 0, buffer, len, p, need_size ) );
return p;
}


使用时注意,要记得delete [] p;有点麻烦,那看第二种:

第二种,使用封装类:

#ifndef AW_TRANS_H
#define AW_TRANS_H
class TCHAR_EXT
{
public:
TCHAR_EXT( char* str )
{
psz_a = NULL;
psz_w = NULL;
int len = strlen( str );
psz_a = new char[len+1];
memset( psz_a, 0, len+1 );
memcpy_s( psz_a, len+1, str, len );


len = strlen( psz_a);
psz_w = NULL;
int need_size = ::MultiByteToWideChar( CP_ACP, 0, psz_a, len, psz_w, 0 );
psz_w = new wchar_t[need_size+1];
wmemset( psz_w, 0, need_size+1 );
need_size = ::MultiByteToWideChar( CP_ACP, 0, psz_a, len, psz_w, need_size );
}
TCHAR_EXT( wchar_t* str )
{
psz_a = NULL;
psz_w = NULL;
size_t len = wcslen( str );
psz_w = new wchar_t[len+1];
wmemset( psz_w, 0, len+1 );
wmemcpy_s( psz_w, len+1, str, len );


len = wcslen( psz_w );
psz_a = NULL;
int need_size = ::WideCharToMultiByte( CP_ACP, 0, psz_w, len, psz_a, 0, NULL, NULL );
psz_a = new char[need_size+1];
memset( psz_a, 0, need_size+1 );
need_size =::WideCharToMultiByte( CP_ACP, 0, psz_w, len, psz_a, need_size, NULL, NULL );
}
char* GetBufferA()
{
if( psz_a ) return psz_a;
return NULL;
}
wchar_t* GetBufferW()
{
if( psz_w ) return psz_w;
return NULL;
}
~TCHAR_EXT()
{
if( psz_a ) { delete [] psz_a; psz_a = NULL; }
if( psz_w ) { delete [] psz_w; psz_w = NULL; }
}
TCHAR_EXT(const TCHAR_EXT& str)
{
if( psz_a ){ delete [] psz_a; psz_a = NULL;}
if( psz_w ){ delete [] psz_w; psz_w = NULL;}
if( str.psz_a )
{
size_t len = strlen( str.psz_a );
psz_a = new char[len+1];
memset( psz_a, 0, len+1 );
memcpy_s( psz_a, len+1, str.psz_a, len );
}
if( str.psz_w )
{
size_t len = wcslen( str.psz_w );
psz_w = new wchar_t[len+1];
wmemset( psz_w, 0, len+1 );
wmemcpy_s( psz_w, len+1, str.psz_w, len );
}
}


TCHAR_EXT& operator = (const TCHAR_EXT& str)
{
if( psz_a ){ delete [] psz_a; psz_a = NULL;}
if( psz_w ){ delete [] psz_w; psz_w = NULL;}
if( str.psz_a )
{
size_t len = strlen( str.psz_a );
psz_a = new char[len+1];
memset( psz_a, 0, len+1 );
memcpy_s( psz_a, len+1, str.psz_a, len );
}
if( str.psz_w )
{
size_t len = wcslen( str.psz_w );
psz_w = new wchar_t[len+1];
wmemset( psz_w, 0, len+1 );
wmemcpy_s( psz_w, len+1, str.psz_w, len );
}
return *this;
}
private:
char* psz_a;
wchar_t* psz_w;
};
#endif



使用很简单:

TCHAR_EXT a("abc我是中国人");
char* psz_a = a.GetBufferA();
wchar_t* psz_w = a.GetBufferW();

自己选择需要的字符串类型,也不用担心内存问题,欢迎批评指正或提出建议

你可能感兴趣的:(ext,null,delete,buffer)