P/Invoke: usually you need CharSet.Auto (via: .NET Column: Calling Win32 DLLs in C# with P/Invoke)
Posted by jpluimers on 2012/02/28
I don’t do P/Invoke often, and somehow I have trouble remembering the value of CharSet to pass with DllImport.
In short, pass CharSet.Auto unless you P/Invoke a function that is specific to CharSet.Ansi or CharSet.Unicode. The default is CharSet.Ansi, which you usually don’t want:
when Char or String data is part of the equation, set the CharSet property to CharSet.Auto. This causes the CLR to use the appropriate character set based on the host OS. If you don’t explicitly set the CharSet property, then its default is CharSet.Ansi. This default is unfortunate because it negatively affects the performance of text parameter marshaling for interop calls made on Windows 2000, Windows XP, and Windows NT®.
The only time you should explicitly select a CharSet value of CharSet.Ansi or CharSet.Unicode, rather than going with CharSet.Auto, is when you are explicitly naming an exported function that is specific to one or the other of the two flavors of Win32 OS. An example of this is the ReadDirectoryChangesW API function, which exists only in Windows NT-based operating systems and supports Unicode only; in this case you should use CharSet.Unicode explicitly.
–jeroen
.NET/C#: Getting volume free space from UNC path requires PInvoke of GetDiskFreeSpaceEx in Kernel32.dll « The Wiert Corner – irregular stream of stuff said
[…] The Charset is almost always CharSet.Auto as that works far better than the default. […]
Warren P said
Does ANYONE care about Win9x anymore?
W
David Heffernan said
If you don’t care about Win 9x, and I don’t, then CharSet.Unicode seems to convey more meaning to me.