Simple: How can I explicitly marshal the result of a WinAPi function ?
I know how to marshal parameters of WinApi functions in C# but how can I also marshal the return values ? Or do I actually have to marshal them ? I understand WinAPi returns only
BOOL
or all types of INT
(handles are int as well in unmanaged code).
// common signature
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
static extern int GetFileAttributes([MarshalAs(UnmanagedType.LPStr)] string filename);
// my prefered signature because easy to handle the result
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
static extern FileAttributes GetFileAttributes([MarshalAs(UnmanagedType.LPStr)] string filename);
Since FileAttributes
is enum and each value can easily be cast to int
I'm sure I'm safe with this notation. But can I marshal the result in this one signature like I do with the parameters ? I actually only know Marshal
class and MarshalAs
attribute.
CharSet.Auto
, but anymore, there's really no reason not to useCharSet.Unicode
unless you're targeting .NET 2.0 and Windows 98. – Cody GrayAnsi
until today when I finally found out how to makeAuto
work. Because it didn't. pinvoke didn't supply my knowledge with enough information about that. Now I have for all my WinApi file-functions all 3 signatures implemented so I can switch between them. If you say Unicode is the way to go. I will remember that and take it into account next time. Ok ? – BitterblueUnmanagedType.LPWStr
for Unicode, andUnmanagedType.LPTStr
for Auto. Or better yet, omit theMarshalAs
attribute altogether and just use the default marshalling. The CLR knows what it's doing for string types. – Cody Gray