问题描述
在维护 COM
接口时,空的 BSTR
是否应该与 NULL
一样对待?换句话说,这两个函数调用是否应该产生相同的结果?
When maintaining a COM
interface should an empty BSTR
be treated the same way as NULL
?In other words should these two function calls produce the same result?
// Empty BSTR
CComBSTR empty(L""); // Or SysAllocString(L"")
someObj->Foo(empty);
// NULL BSTR
someObj->Foo(NULL);
推荐答案
是的 - NULL BSTR 与空 BSTR 相同.我记得当我们从 VS6 切换到 2003 时,我们发现了各种各样的错误 - CComBSTR 类对使用 NULL 而不是空字符串分配它的默认构造函数进行了更改.例如,当您将 BSTR 视为常规 C 样式字符串并将其传递给诸如 strlen
之类的函数,或尝试用它初始化 std::string
时,就会发生这种情况.
Yes - a NULL BSTR is the same as an empty one. I remember we had all sorts of bugs that were uncovered when we switched from VS6 to 2003 - the CComBSTR class had a change to the default constructor that allocated it using NULL rather than an empty string. This happens when you for example treat a BSTR as a regular C style string and pass it to some function like strlen
, or try to initialise a std::string
with it.
Eric Lippert 在 Eric 的 BSTR 语义完整指南:
Eric Lippert discusses BSTR's in great detail in Eric's Complete Guide To BSTR Semantics:
让我先列出差异,然后然后讨论中的每一点令人痛苦的细节.
BSTR 必须具有相同的NULL 和"的语义.一个 PWSZ经常有不同的语义那些.
A BSTR must have identicalsemantics for NULL and for "". A PWSZfrequently has different semantics forthose.
必须分配和释放 BSTR与 SysAlloc* 系列职能.PWSZ 可以是从自动存储缓冲区堆栈或使用 malloc、new、LocalAlloc 或任何其他内存分配器.
A BSTR must be allocated and freedwith the SysAlloc* family offunctions. A PWSZ can be anautomatic-storage buffer from thestack or allocated with malloc, new,LocalAlloc or any other memoryallocator.
BSTR 是固定长度的.一个 PWSZ可以是任意长度,仅受以下限制它的有效内存量缓冲区.
A BSTR is of fixed length. A PWSZmay be of any length, limited only bythe amount of valid memory in itsbuffer.
BSTR 总是指向第一个缓冲区中的有效字符.一个 PWSZ可能是指向中间或结尾的指针字符串缓冲区.
A BSTR always points to the firstvalid character in the buffer. A PWSZmay be a pointer to the middle or endof a string buffer.
在分配 n 字节 BSTR 时,您有空间容纳 n/2 个宽字符.当您为 PWSZ 分配 n 个字节时您可以存储 n/2 - 1 个字符 --你必须为空值留出空间.
When allocating an n-byte BSTR youhave room for n/2 wide characters.When you allocate n bytes for a PWSZyou can store n / 2 - 1 characters --you have to leave room for the null.
BSTR 可以包含任何 Unicode 数据包括零字符.一个 PWSZ从不包含零字符除了作为字符串结束标记.BSTR 和 PWSZ 总是有一个最后一个有效字符后的零字符字符,但在 BSTR 中是有效的字符可能是零字符.
A BSTR may contain any Unicode dataincluding the zero character. A PWSZnever contains the zero characterexcept as an end-of-string marker.Both a BSTR and a PWSZ always have azero character after their last validcharacter, but in a BSTR a validcharacter may be a zero character.
一个 BSTR 实际上可能包含一个奇数字节数——它可以用于移动二进制数据.PWSZ 是几乎总是偶数字节并且仅用于存储 Unicode字符串.
A BSTR may actually contain an oddnumber of bytes -- it may be used formoving binary data around. A PWSZ isalmost always an even number of bytesand used only for storing Unicodestrings.
这篇关于空 BSTR 和 NULL BSTR 之间应该有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!