宽字符与ANSI字符之间的相互转换

目前知道有两种方式:可以提供宽字符与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库给字符串分配的内存,标准库提供的函数则要求自己事先非配一个缓存区用来存放,转换后的字符串.

欢迎讨论...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值