I'm new to COM. According to http://msdn.microsoft.com/en-us/library/windows/desktop/ms221069(v=vs.85).aspx BSTR is a string with prefix. I am wondering what it the purpose for BSTR. In which case we have to use BSTR instead of string type? If someone could have an example please? Thanks
2 Answers
BSTR
is standard string type in wide family of APIs:
A BSTR (Basic string or binary string) is a string data type that is used by COM, Automation, and Interop functions. Use the BSTR data type in all interfaces that will be accessed from script.
You use BSTR
when you have to, esp. when API you are using expects that you pass BSTR
; e.g. when certain COM interface method requires BSTR
argument. You use BSTR
or anything else at your discretion when you have choices.

- 68,205
- 6
- 94
- 158
First of all, sometimes you have to use BSTR. For example, if you call a COM method and the callee expects a BSTR you'd rather not pass any other string type - otherwise they could call SysStringLen()
and run into undefined behavior. Use BSTR when an API descriptions says you should use BSTR.
Also BSTR
has these useful features:
- (the most important thing) It is allocated on a separate heap managed by COM and so if your application consists of different modules using different runtime heaps any module can allocate a BSTR and any module can then free it easily which is not the case with other dynamically allocated stuff. This is very useful for cases when for example you pass an existing string, the callee has to either preserve or reallocate it - without the single heap and the single set of allocation functions you'd have a hard time doing that.
- (the less important thing) it's supported by Automation marshaller so you can easily use it in COM interfaces that must be marshalled and not bother crafting and registering the proxy-stubs stuff
- (the least important IMO) it can contain embedded null characters unlike other typical string types

- 167,383
- 100
- 513
- 979
-
If you have code sample for this example please: "This is very useful for cases when for example you pass an existing string, the callee has to either preserve or reallocate it - without the single heap and the single set of allocation functions you'd have a hard time doing that." – user454083 May 12 '14 at 09:00
-
@user454083: Any case with "in-out" parameter - the callee can either leave the passed parameter unchanged or set a new value. – sharptooth May 12 '14 at 12:09