char 与 wchar_t 转换

时间:2021-08-04 20:14:50
//将wchar_t* 转成char*
int w2c( const wchar_t *pwc_str, char *pc_outstr, int i_coutlen )
{
	if ( pwc_str )
	{
		int i_wclen = wcslen( pwc_str );

		//获取转换后的长度
		int i_reallen = WideCharToMultiByte( 0, // specify the code page used to perform the conversion
		0,         // no special flags to handle unmapped characters
		pwc_str,     // wide character string to convert
		i_wclen,   // the number of wide characters in that string
		NULL,      // no output buffer given, we just want to know how long it needs to be
		0,
		NULL,      // no replacement character given
		NULL );    // we don't want to know if a character didn't make it through the translation

		// make sure the buffer is big enough for this, making it larger if necessary
		if( i_reallen >= i_coutlen )
			i_reallen = i_coutlen - 1;

		// transform unicode to ascii
		WideCharToMultiByte( 0, // specify the code page used to perform the conversion
		0,         // no special flags to handle unmapped characters
		pwc_str,   // wide character string to convert
		i_wclen,   // the number of wide characters in that string
		pc_outstr, // put the output ascii characters at the end of the buffer
		i_reallen,                           // there is at least this much space there
		NULL,      // no replacement character given
		NULL );
		pc_outstr[i_reallen] = 0;
		return 0;
	}
	return -1;
}

//将char* 转成wchar_t*
int c2w( const char *pc_str, wchar_t *pwc_outstr, int i_wcoutlen )
{
	if( pc_str )
	{
		int i_clen = strlen( pc_str );
		
		//获取转换后的长度
		int i_reallen = MultiByteToWideChar( CP_ACP, 0, pc_str,(int)i_clen, NULL, 0 );
		if( i_reallen >= i_wcoutlen )
			i_reallen = i_wcoutlen - 1;
		MultiByteToWideChar( CP_ACP, 0, pc_str, i_clen, pwc_outstr, i_reallen );
		pwc_outstr[i_reallen] = 0;
		return 0;
	}
	return -1;
}