问题
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.
回答1:
Yes you can. You just need to use the [return:]
attribute syntax, for example:
[return: MarshalAs(UnmanagedType.LPStruct)]
But in your case, there is no marshalling to do. Marshalling is not needed to convert integral types like that, so just use the second form in your example.
If you really want, you could write a public method that called GetFileAttributes()
which checked the return value for validity.
来源:https://stackoverflow.com/questions/17879121/how-to-marshal-return-values-of-winapi-functions