【发布时间】:2017-03-11 23:40:54
【问题描述】:
我是 C# 新手,所以我查看了 this 问题,但我仍然不确定在编组 GetWindoInfo() 的第二个参数时是否应该在此处包含 ref 关键字使用 p/invoke 调用 Win32 API:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", EntryPoint = "GetWindowInfo", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool GetWindowInfo(IntPtr hwnd, [MarshalAs(UnmanagedType.Struct)] ref tagWINDOWINFO pwi);
来自 MSDN documentation ref:
ref 关键字导致参数通过引用传递,而不是通过 价值。
所以在这种情况下,我上面的代码似乎是正确的,对吧?将编组子句改为编组 UnmanagedType.LPStruct 并删除 ref 关键字会导致相同的结果吗?像这样:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", EntryPoint = "GetWindowInfo", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool GetWindowInfo(IntPtr hwnd, [MarshalAs(UnmanagedType.LPStruct)] tagWINDOWINFO pwi);
来自 MSDN documentation 获取 GetWindowInfo 函数:
BOOL WINAPI GetWindowInfo(
_In_ HWND hwnd,
_Inout_ PWINDOWINFO pwi
);
编辑:
正如答案中的 cmets 所述,第一个代码示例是正确的。第二个代码块是不正确的,因为指针传递和引用传递是不同的,反映了我的一个基本误解。我在考虑 C++ 取消引用。有关更多信息,请参阅this 问题。
【问题讨论】:
-
我阅读了您问题的第一部分“我是 C# 的新手...”并查看了您的示例代码,然后我想,“也许 Windows API 不是最好的起点”。然后我看到你有使用 C++ 的经验,并意识到你对编程并不陌生,只是 C#。继续。
标签: c# pinvoke marshalling ref