Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, you might not actually have to do anything at all, if all you need to do is read the contents. A BSTR type is a pointer to a null-terminated wchar_t array already. In fact, if you check the headers, you will find that BSTR is essentially defined as:</p> <pre><code>typedef BSTR wchar_t*; </code></pre> <p>So, the compiler can't distinguish between them, even though they have different semantics.</p> <p>There is are two important caveat.</p> <ol> <li><p><s>BSTRs are supposed to be immutable. You should never change the contents of a BSTR after it has been initialized. If you "change it", you have to create a new one assign the new pointer and release the old one (if you own it).</s><br> <i>[<strong>UPDATE</strong>: this is not true; sorry! You can modify BSTRs in place; I very rarely have had the need.]</i></p></li> <li><p>BSTRs are allowed to contain embedded null characters, whereas traditional C/C++ strings are not.</p></li> </ol> <p>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.</p> <p>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:</p> <pre><code>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 </code></pre> <p>If you are using class wrappers for your BSTR, the wrapper should have a way to call SysStringLen() for you. For example:</p> <pre><code>CComBString use .Length(); _bstr_t use .length(); </code></pre> <p><strong>UPDATE</strong>: This is a good article on the subject by someone far more knowledgeable than me:<br> <a href="http://blogs.msdn.com/ericlippert/archive/2003/09/12/52976.aspx" rel="nofollow noreferrer">"Eric [Lippert]'s Complete Guide To BSTR Semantics"</a></p> <p><strong>UPDATE</strong>: Replaced strcpy() with wcscpy() in example</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload