Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

.net

com

rcw

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?

like image 841
richard Avatar asked Jun 21 '11 00:06

richard


1 Answers

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

like image 111
joncham Avatar answered Nov 15 '22 05:11

joncham