目前知道有两种方式:可以提供宽字符与ANSI字符之间的转换,
第一种由COM库提供的函数
char* _com_util::ConvertBSTRToString(BSTR );
BSTR _com_util::ConvertStringToBSTR(char*);
Example
// ConvertBSTRToString.cpp
#include <comutil.h>
#include <stdio.h>
#pragma comment(lib, "comsupp.lib")
int main()
{
BSTR bstrText = ::SysAllocString(L"Test");
wprintf(L"BSTR text: %s\n", bstrText);
char* lpszText2 = _com_util::ConvertBSTRToString(bstrText);
printf("char * text: %s\n", lpszText2);
SysFreeString(bstrText);
delete[] lpszText2;
}
Output
BSTR text: Test
char * text: Test
第二种标准库提供的函数
将宽字符串wcstr转换为ANSI字符串mbstr
size_t wcstombs( char *mbstr, const wchar_t *wcstr, size_t count );
mbstr
多字节字符的地址
wcstr
宽字符的地址
count
可以存储在多字节字符的最大字节数
将ANSI字符串mbstr转化为宽字符串wcstr
size_t mbstowcs( wchar_t *wcstr, const char *mbstr, size_t count );
Parameters
wcstr
宽字符串的地址
mbstr
多字节字符串(ANSI)的地址
count
要转换的多字节的字符的个数
Example
/* MBSTOWCS.CPP illustrates the behavior of the mbstowcs function
*/
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
int i;
char *pmbnull = NULL;
char *pmbhello = (char *)malloc( MB_CUR_MAX );
wchar_t *pwchello = L"Hi";
wchar_t *pwc = (wchar_t *)malloc( sizeof( wchar_t ));
printf( "Convert to multibyte string:\n" );
i = wcstombs( pmbhello, pwchello, MB_CUR_MAX );
printf( "\tCharacters converted: %u\n", i );
printf( "\tHex value of first" );
printf( " multibyte character: %#.4x\n\n", pmbhello );
printf( "Convert back to wide-character string:\n" );
i = mbstowcs( pwc, pmbhello, MB_CUR_MAX );
printf( "\tCharacters converted: %u\n", i );
printf( "\tHex value of first" );
printf( " wide character: %#.4x\n\n", pwc );
delete[] pmbhello;
delete[] pwc ;
//该例子示例摘自msdn,我觉得这里有内存泄漏,所以我加入了
//最后两行,应为这里涉及到动态内存分配,
//ms-help://MS.MSDNQTR.2003FEB.2052/wcecrt/htm/_wcecrt_mbstowcs.htm
}
Output
Convert to multibyte string:
Characters converted: 1
Hex value of first multibyte character: 0x0e1a
Convert back to wide-character string:
Characters converted: 1
Hex value of first wide character: 0x0e1e
用COM库的函数需要在转换完后,自己释放由COM库给字符串分配的内存,标准库提供的函数则要求自己事先非配一个缓存区用来存放,转换后的字符串.