dahall / Vanara

A set of .NET libraries for Windows implementing PInvoke calls to many native Windows APIs with supporting wrappers.
MIT License
1.75k stars 190 forks source link

Using char[] in place of StringBuilder #415

Closed shravan2x closed 1 year ago

shravan2x commented 1 year ago

There seems to be a small perf advantage to using char[] instead of StringBuilder for P/Invoke. See https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1838 . Is there a reason to prefer StringBuilder that I don't understand?

dahall commented 1 year ago

I hadn't read this before. Thanks. I need to do some testing around this. One area of testing is that StringBuilder will morph to Ansi or Unicode based on the CharSet property of DllImport. If I can consistently make char[] work, I can add overloads to accommodate. When I started this work, I was trying avoid unsafe code and Span had not yet been introduced.

dahall commented 1 year ago

It appears, after some reading and testing, that char[] only works for methods that use only Unicode. For ANSI or platform dependent methods using CharSet.Auto or CharSet.Ansi, StringBuilder and String are the only supported classes for default marshaling.