What is the difference between a COM string (BSTR) and a .NET string?
Asked Answered
F

1

6

Is it just the way the bytes are combined to "encode" the data?

I'm curious because I wonder how an RCW automatically takes a .NET string and transforms it into a COM BSTR. I'm guessing it just forms a valid COM BSTR transformed from the .NET string.

Related: Could I construct my own valid BSTR using a byte type in .NET?

Fish answered 21/6, 2011 at 0:34 Comment(0)
G
10

The two string types are not related at all. A transformation has to occur to convert one type to another.

A BSTR has a number of conventions that must be followed in including allocated via SysAllocString*, deallocated with SysFreeString, having a length prefix, and a terminator of two null characters.

http://msdn.microsoft.com/en-us/library/ms221069.aspx

A .Net string is a managed type that is allocated via the managed heap. It's lifetime is managed by the CLR garbage collector.

To construct your own BSTR, it would be much better to use Marshal.StringToBSTR:

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtobstr.aspx

If that's not good enough you can pinvoke SysAllocString:

http://msdn.microsoft.com/en-us/library/ms221458.aspx

Glossary answered 21/6, 2011 at 0:39 Comment(3)
Thanks joncham. Very helpful. I guess I'm just wondering what would the differences be if I inspected the bits and bytes. They both get stored somewhere. They both represent something. Aren't they just different bits and bytes to represent the same thing (a string of characters?)Fish
Yes, all data is just bytes ;-). The problem is who allocates/deallocates those bytes, and the conventions used when laying out those bytes. For example, when allocating a BSTR you don't actually retrieve a pointer to the start of the allocated memory. Your pointer is 4 bytes into the allocated space, since the first four bytes store the length of the string.Glossary
@Richard DesLonde: yea, they are both arrays of characters. However, you can't really use any string of characters as a System.String, since any constructor to System.String will copy the character array to another memory location.Beiderbecke

© 2022 - 2024 — McMap. All rights reserved.