Defining how types should be marshaled via a P/Invoke or COM interop is difficult to get correct and many bad practices have been developed over the years. The Native interoperability best practices page should be converted into an analyzer to help developers do the right thing.
Related to https://github.com/dotnet/runtime/issues/33808
Additional thoughts:
ComImport should be scrutinized./cc @terrajobst @jkoritzinsky @elinor-fung
There may be more in
https://github.com/dotnet/runtime/blob/master/docs/coding-guidelines/interop-guidelines.md
https://github.com/dotnet/runtime/blob/master/docs/coding-guidelines/interop-pinvokes.md (which I'll merge into the former)
Of course, anything unique in those would be candidates for adding to the official doc as well.
There is an existing P/Invoke analyzer, which could be a fitting home for some of this.
Some marshalling-related items that could be reasonable rules from the guidance doc:
CharSet on DllImport when strings/characters are presentstring and StringBuilder, not char), although it is under Globalization(?) and the doc talks about security / partial trustExactSpelling=true on DllImport (Performance)[Out] string (Interoperability)StringBuilder parameters (Performance)SizeConst when marshalling field as ByValArray (Interoperability) Delegate or MulticastDelegate fields in marshalled structs (Interoperability).@elinor-fung Here is another issue that should get a rule: https://github.com/dotnet/runtime/issues/9944
Some initial thoughts:
[ComVisible] and [ComImport] on an interface should be incorrect, right?[MarshalAs] for string and object as they are often _not_ BSTR and VARIANT@elinor-fung Is this aggregated issue being handled by the various other issues being filed or should we keep this one open?
Closing this and using #37039 as the tracking issue that will point to the separate issues we file for each rule.
Most helpful comment
There is an existing P/Invoke analyzer, which could be a fitting home for some of this.
Some marshalling-related items that could be reasonable rules from the guidance doc:
CharSetonDllImportwhen strings/characters are presentstringandStringBuilder, notchar), although it is under Globalization(?) and the doc talks about security / partial trustExactSpelling=trueonDllImport(Performance)[Out] string(Interoperability)StringBuilderparameters (Performance)SizeConstwhen marshalling field asByValArray(Interoperability)DelegateorMulticastDelegatefields in marshalled structs (Interoperability).