我正在尝试以传递标志的方式PInvoke CreateDesktop,以通过子进程继承桌面。声明如下:
[DllImport("user32", EntryPoint = "CreateDesktopW", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateDesktop(string lpszDesktop, IntPtr lpszDevice, IntPtr pDevmode, int dwFlags,
int dwDesiredAccess, [MarshalAs(UnmanagedType.LPStruct)] SECURITY_ATTRIBUTES lpsa);
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
我使用它如下:
Win32.SECURITY_ATTRIBUTES sa = new Win32.SECURITY_ATTRIBUTES();
sa.nLength = Marshal.SizeOf(sa);
sa.bInheritHandle = 1;
testDesktopHandle = Win32.CreateDesktop(name, IntPtr.Zero, IntPtr.Zero, 0, Win32.GENERIC_ALL, sa);
而且不幸的是它不起作用,我收到以下错误:
System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #6': Invalid managed/unmanaged type combination (this value type must be paired with Struct).
有什么想法我做错了吗?
最佳答案
尝试将参数#6更改为
static extern IntPtr CreateDesktop(..., [In] ref SECURITY_ATTRIBUTES lpsa);
(这会编译,并且在运行时不会引发异常,但是我仅使用伪参数对其进行了测试。)
与CreateDesktop的C ++声明进行比较:
HDESK WINAPI CreateDesktop(..., __in_opt LPSECURITY_ATTRIBUTES lpsa);
↑ ↑ ↑
[In] ref SECURITY_ATTRIBUTES lpsa
LP
代表“长指针”,即LPSECURITY_ATTRIBUTES
是指向SECURITY_ATTRIBUTES
结构的指针。因此,在C#中,您需要通过引用传递您的struct实例(值类型)。