VC学习四:关于 BSTR, CComBSTR and _bstr_t

 

BSTR是COM中默认的字符串数据格式,和char* 及std::string等不同,BSTR is a null-terminated, length-prefixed, unicode string.

下面是一个非常好的对BSTR的解释: A bstr is a pointer to a string of wide char. The string is not terminated. Instead, the length of the string is stored as an unsigned long just before the first character of the string.  (这一点和普通的 *char很不同,因为*char 指针指向的是该串的第一个字符,而bstr的指针是指向该字符串的长度) You might think that you could create a bstr the c++ way, by creating a structure and then returning a pointer to the second element, cast to bstr, but you should never do this! the memory pointed to by a bstr is actually owned by Windows.  Becaust a bstr's memory is owned by Windows, you can safely pass a bstr between processes. Instead, you can use the function SysAllocString() to create a bstr, and the function SysFreeString() to destroy it properly. In fact, you should only use platform SDK functions (or helper classes that use them internally) to manipulate bstrs.

缺点: most of the string manipulation functions normaly taken for granted, such as finding a substring, comparing two strings, and so on, are missing. Most significantly, there seems to be no function to copy a bstr. 

 CComBSTR: 是ATL中的一个类, this class is wrapper for BSTR,

_bstr_t:  是BSTR的封装类,实际上是一个smart pointer, it encapsulates the BSTR date type. It manages resource allocation and deallocation through function calls to SysAllocString / SysFreeString and other BSTR APIs.  _bstr_t 其实相当于一个带有引用计数的智能指针。

 _bstr_t: is "native COM support" class. And CComBSTR is the ATL class. the two classes are very similar. Both will take care of allocating and deallocating the wrapped bstr in the class constructor and destructor.  They also can  be used to take charge of an existing bstr with the Attach() method, or can be made to abandon the bstr with Detach() method. The have helpful operators and methods to compare two string, copy a string, and so on. In many cases, _bstr_t and CComBSTR instances can be passed as bstr substitues. ( 但要注意:有时候不恰当的使用这两个类来代替bstr有可能会造成内存泄露)

CComBSTR和 _bstr_t 都是BSTR的wrapper,但实现机制不同, _bstr_t更通用些,不过如果使用ATL的话,可能 CComBSTR更方便些。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值