问题描述
我有一个BSTR对象,我想转换为复制到一个wchar__t对象。棘手的事情是BSTR对象的长度可以是从几千字节到几百千字节的任何地方。有没有一种有效的方式来复制数据?我知道我可以只声明一个wchar_t数组,并始终分配最大可能的数据,它需要持有。然而,这意味着为可能只需要几千字节的东西分配几百千字节的数据。任何建议?
首先,你可能不需要做任何事情,如果你需要做的是阅读内容。 BSTR类型是一个指向空终止的wchar_t数组的指针。事实上,如果你检查头,你会发现BSTR基本上定义为:
typedef BSTR wchar_t *;
因此,编译器不能区分它们,即使它们有不同的语义。 >
有两个重要的警告。
-
[
[UPDATE: this is not true; sorry! You can modify BSTRs in place; I very rarely have had the need.] BSTRs are allowed to contain embedded null characters, whereas traditional C/C++ strings are not.
If you have a fair amount of control of the source of the BSTR, and can guarantee that the BSTR does not have embedded NULLs, you can read from the BSTR as if it was a wchar_t and use conventional string methods (wcscpy, etc) to access it. If not, your life gets harder. You will have to always manipulate your data as either more BSTRs, or as a dynamically-allocated array of wchar_t. Most string-related functions will not work correctly.
Let's assume you control your data, or don't worry about NULLs. Let's assume also that you really need to make a copy and can't just read the existing BSTR directly. In that case, you can do something like this:
UINT length = SysStringLen(myBstr); // Ask COM for the size of the BSTR
wchar_t *myString = new wchar_t[lenght+1]; // Note: SysStringLen doesn't
// include the space needed for the NULL
wcscpy(myString, myBstr); // Or your favorite safer string function
// ...
delete myString; // Done
If you are using class wrappers for your BSTR, the wrapper should have a way to call SysStringLen() for you. For example:
CComBString use .Length();
_bstr_t use .length();
UPDATE: This is a good article on the subject by someone far more knowledgeable than me:
"Eric [Lippert]'s Complete Guide To BSTR Semantics"UPDATE: Replaced strcpy() with wcscpy() in example
这篇关于你如何有效地复制BSTR到wchar_t []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!