BSTR与wchar_t*的真正区别

spdia 2001-02-13 01:35:00
typedef /* [wire_marshal] */ OLECHAR __RPC_FAR *BSTR; in wtypes.h
typedef WCHAR OLECHAR; in wtypes.h
typedef wchar_t WCHAR; in winnt.h
typedef unsigned short wchar_t; in ctype.h


wchar_t wstrsource[16]=L"hello world";
BSTR bstrhello=::SysAllocString(wstrsource);
cout<<::SysStringLen(bstrhello)<<"\n";
cout<<::SysStringLen(wstrsource)<<"\n";

RESULT
11
2720172

wchar_t wstrsource[16]=L"hello\0world";
BSTR bstrhello=::SysAllocString(wstrsource);
cout<<::SysStringLen(bstrhello)<<"\n";
cout<<::SysStringLen(wstrsource)<<"\n";

RESULT
5
2720172

Q1:为什么会出现这样的结果?SysAllocString怎么判断字符串结束?'\0'会在"hello world"后自动添加?
Q2:BSTR与wchar_t *的区别?
Q3:wchar_t wstrsource[16]=L"hello\0world";中L的作用?
...全文
611 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
spdia 2001-02-13
  • 打赏
  • 举报
回复
原来如此,我明白了.谢谢各位!!!!
Fesd 2001-02-13
  • 打赏
  • 举报
回复
Q1: 根据'\0'判断字符串结束
Q2: wchar_t* 只是一个简单的指针 跟int* ,char* 一样
BSTR 所指向的内存地址相当于一个wchar_t*,但BSTR往后退4Bytes(在内存中)的
地址中所存的一个DWORD值表示它的长度。

例如:
BSTR bstrT = ::SysAllocString(L"....");//(内存地址)0x00001000;
LPDWORD lpdwLen = (LPBYTE)bstrT - 4; //(相当于0x0000FFC)
ASSERT(*lpdwLen == ::SysStringLen(bstrT);

注意:SysStringLen的参数类型是BSTR而非wchar_t*

Q3: L""告诉编译器把双引号中的字符串按双字节(wchat_t)处理
rockswang 2001-02-13
  • 打赏
  • 举报
回复
下面是直接从MSDN里copy来的,注意最后一句。

SysAllocStringLen
BSTR SysAllocStringLen(
OLECHAR FAR* pch,
unsigned int cch
);

Allocates a new string, copies cch characters from the passed string into it, and then appends a null character.

Note: This function does NOT convert a char * string into a unicode BSTR. The BSTR returned with this function can only be used with 16 bit applications.

Parameters
pch
A pointer to cch characters to copy, or Null to keep the string uninitialized.
cch
Number of characters to copy from pch. A null character is placed afterwards, allocating a total of cch+1 characters.
随风bj 2001-02-13
  • 打赏
  • 举报
回复
1.一般以'\0'判断字符串结束(也就是NULL),在初始化字符串时每个空的位置都是0
2.
3.将字符串转换为通用的ascii码值

16,548

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • AIGC Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧