How To Marshal Return Values Of WinApi Functions?

痞子三分冷 提交于 2020-01-21 07:51:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!