What is the equivalent of _bstr_t in C#

寵の児 提交于 2020-01-02 12:20:49

问题


I am working on a project where I need to convert C++ code to C#.

I came across _bstr_t in the code I would like to know how the equivalent in C#.


回答1:


The _bstr_t class is a wrapper for the BSTR type. This is a string in OLE Automation that is standardized across languages.

That said, the equivalent type in .NET is a System.String.

The key is when interacting with it (or defining your interfaces for COM interop in .NET code), you'll want to use the MarshalAsAttribute with a value from the UnmanagedType enumeration of UnmanagedType.BStr, like so:

// This is on an interface that is in unmanaged code.
public void DoSomething([MarshalAs(UnmanagedType.BStr] string myString);

Note that if your class is actually exposing the _bstr_t in a COM interface, then you should change it to expose a BSTR; _bstr_t is a helper class that isn't meant to be exposed across interface boundaries. The BSTR is for that and the methods on _bstr_t are for handling the allocation and use of BSTR instances.




回答2:


If you are just converting code, use string

If you are interfacing with C++ code through PInvoke, you will probably declate the parameter as a string and put [MarshalAs(UnmanagedType.BStr)] in front of the parameter declaration:

[DllImport("OldCLib.Dll")]
public static extern void PassBStr([MarshalAs(UnmanagedType.BStr)] string s); 


来源:https://stackoverflow.com/questions/13256440/what-is-the-equivalent-of-bstr-t-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!