简单:如何明确封送WinAPi函数的结果?
我知道如何在C#中编组WinApi函数的参数但是我如何编组返回值呢? 或者我真的要整理它们吗? 我理解WinAPi只返回 BOOL或所有类型的 INT (句柄在非托管代码中也是int)。 // 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);
因为FileAttributes是枚举的,并且每个值都可以很容易地转换为int所以我确信这个符号是安全的。 但是我可以像参与参数一样编组这个签名中的结果吗? 我实际上只知道Marshal类和MarshalAs属性。
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.
最满意答案
是的你可以。 您只需要使用[return:]属性语法,例如:
[return: MarshalAs(UnmanagedType.LPStruct)]但在你的情况下,没有编组要做。 转换整数类型不需要编组,因此只需使用示例中的第二种形式。
如果你真的想要,你可以写一个名为GetFileAttributes()的公共方法,它检查有效性的返回值。
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.
更多推荐
发布评论