简体   繁体   English

COM字符串(BSTR)和.NET字符串之间有什么区别?

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

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. 我很好奇,因为我想知道RCW如何自动获取.NET字符串并将其转换为COM BSTR。 I'm guessing it just forms a valid COM BSTR transformed from the .NET string. 我猜它只是形成一个从.NET字符串转换而来的有效COM BSTR。

Related: Could I construct my own valid BSTR using a byte type in .NET? 相关:我可以使用.NET中的字节类型构建自己的有效BSTR吗?

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. BSTR具有许多必须遵循的约定,包括通过SysAllocString *分配,用SysFreeString解除分配​​,具有长度前缀和两个空字符的终止符。

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

A .Net string is a managed type that is allocated via the managed heap. .Net字符串是通过托管堆分配的托管类型。 It's lifetime is managed by the CLR garbage collector. 它的生命周期由CLR垃圾收集器管理。

To construct your own BSTR, it would be much better to use Marshal.StringToBSTR: 要构建自己的BSTR,使用Marshal.StringToBSTR要好得多:

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

If that's not good enough you can pinvoke SysAllocString: 如果这还不够好,你可以调用SysAllocString:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM