如何制作WinApi函数的返回值?(How To Marshal Return Values Of WinApi Functions?)

系统教程 行业动态 更新时间:2024-06-14 16:59:17
如何制作WinApi函数的返回值?(How To Marshal Return Values Of WinApi Functions?)

简单:如何明确封送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.

更多推荐

本文发布于:2023-04-16 14:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/86ccaa3e17c6f15f65b0f77d81e68cf0.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值   WinApi   Marshal   Functions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!