How do you efficiently copy BSTR to wchar_t []?

I have a BSTR object that I would like to convert to copy to a wchar__t object. The difficulty is that the length of a BSTR object can range from a few kilobytes to several hundred kilobytes. Is there an efficient way to copy data? I know that I can simply declare a wchar_t array and always allocate the maximum possible data that he will ever need. However, this would mean allocating hundreds of kilobytes of data for something that could potentially only require a few kilobytes. Any suggestions?

+5
source share
5 answers

First, you don’t need to do anything at all if you only need to read the contents. The BSTR type is already a pointer to a wchar_t array with zero completion. In fact, if you check the headers, you will find that the BSTR is essentially defined as:

typedef BSTR wchar_t*;

Thus, the compiler cannot distinguish between them, even if they have different semantics.

There are two important questions.

  • BSTR must be unchanged. You should never modify the contents of a BSTR after it has been initialized. If you β€œchange it,” you need to create a new one, assign a new pointer and release the old one (if you own it).
    [ UPDATE : this is not true; Sorry! You can change the BSTR in place; I very rarely needed.]

  • BSTRs are allowed to contain embedded null characters, while traditional C / C ++ strings are not.

BSTR , BSTR NULL, BSTR, wchar_t, (wcscpy, ..) . , . BSTR, wchar_t. .

, NULL. , BSTR. - :

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

BSTR, SysStringLen() . :

CComBString    use .Length();
_bstr_t        use .length();

. - , :
"Eric [Lippert] BSTR"

UPDATE: strcpy() wcscpy()

+7

BSTR , . , , , , .

+5

. BSTR . . BSTR Unicode (UTF-16/UCS-2). -, "ANSI BSTR" - API, .

, BSTR , wchar_t.

Visual Studio 2008 , BSTR unsigned short, wchar_t - . wchar_t /Zc:wchar_t.

+4

, BSTR . .

+3

ATL CStringT, . USES_CONVERSION, , , .

0
source

All Articles