BSTRs
BSTR parameters and return values are copied to and from strings by default. --bstr-marshalling selects another
representation, e.g. to read a large string without copying it or to keep the exact length of a BSTR that holds binary data:
| Value | BSTR |
|---|---|
string (default) |
string? (BStrStringMarshaller) |
wrapper |
ComBstr?, which wraps the BSTR without copying it |
none |
the BSTR pointer (nint) |
// --bstr-marshalling wrapper
using ComBstr? xml = document.GetXml();
ReadOnlySpan<char> characters = xml!.AsSpan(); // valid until disposed; ToString() copies, AsBytes() gives the bytes
using var name = ComBstr.Create("Shape 1"); // or CreateFromBytes for binary data
shape.Name = name;
ComBstr is disposable and follows the same ownership rules as ComSafeArray<T>: passed strings stay owned by the
caller, returned strings are owned by the receiver, a string replaced by the callee of an [in, out] parameter is detached, and
COM objects implemented in .NET receive views that are only valid during the call. ComBstr.FromPointer wraps a BSTR, e.g. a
structure field, and Detach gives the pointer up.
- Default values: a
ComBstrornintparameter cannot have a string as its C# default value, soBSTRparameters with adefaultvaluebecome required, together with the optional parameters before them, unless overloads are generated. - Events: dual event interfaces can also be invoked through
IDispatch::Invoke, which passesBSTRs inVARIANTs. In thewrapperandnonemodes, their events withBSTRparameters are only received through the vtable. - Other places: structure fields are
ComBstrValues (see Structures), ornintwithnone, and late-bound wrappers, dispinterface events,VARIANTs, the elements ofSAFEARRAYs and constants usestring. AComBstrpassed to aVARIANTparameter is passed as a copy.