我正在尝试以传递标志的方式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).
任何想法我做错了什么?
答案 0 :(得分:5)
尝试将参数#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实例(值类型)。
答案 1 :(得分:1)
请考虑使用以下原型:
[DllImport("user32", EntryPoint = "CreateDesktopW", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateDesktop(string lpszDesktop, IntPtr lpszDevice, IntPtr pDevmode, int dwFlags,
int dwDesiredAccess, IntPtr lpsa);
然后调用它只是创建一个固定句柄:
GCHandle handle = GCHandle.Alloc(myStruct);
try {
IntPtr pinnedAddress = handle.AddrOfPinnedObject();
}
finally {
handle.Free();
}
这对于使用结构调用PInvoke'd方法非常有效。