Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top