How to return marshal values โ€‹โ€‹of WinApi functions?

Simple: How can I explicitly marshal the result of a WinAPi function?


I know how to marshal WinApi function parameters in C #, but how can I also marshal return values? Or should I really marshal them? I understand that WinAPi returns only BOOL or all INT types (descriptors are also int 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 an enumeration, and each value can be easily ported to INT , I'm sure I'm safe with these notations. But can I marshal the result in this one signature, as with the parameters? I really only know the Marshal and MarshalAs .

+4
source share
1 answer

Yes, you can. You just need to use the attribute syntax [return:] , for example:

 [return: MarshalAs(UnmanagedType.LPStruct)] 

But in your case there are no attempts to do this. Marshalling is not needed to convert such integral types, so just use the second form in your example.

If you really want to, you can write a public method called GetFileAttributes() that checks the return value for validity.

+4
source

Source: https://habr.com/ru/post/1493641/


All Articles