.NET:如何PInvoke UpdateProcThreadAttribute

我试图在Windows 7上PInvoke UpdateProcThreadAttribute()但我的尝试只是返回FALSE与最后Win32错误50。

 Function declaration (from MSDN) BOOL WINAPI UpdateProcThreadAttribute( __inout LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, __in DWORD dwFlags, __in DWORD_PTR Attribute, __in PVOID lpValue, __in SIZE_T cbSize, __out_opt PVOID lpPreviousValue, __in_opt PSIZE_T lpReturnSize ); 

这是我对PInvoke签名的尝试:

 [DllImport("kernel32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true)] public static extern bool UpdateProcThreadAttribute ( IntPtr lpAttributeList, UInt32 dwFlags, ref UInt32 Attribute, ref IntPtr lpValue, ref IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize ); 

这个宣言是否明智? 谢谢。

您的声明有一些问题,但是给您不支持的错误的是Attribute参数。 DWORD_PTR不是一个指针,而是一个指定大小的无符号整数的指针,因此它应该是一个IntPtr而不是refint它。

我将使用的声明是:

  [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UpdateProcThreadAttribute( IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize); 

编辑:

我尝试将此作为注释,但不需要编写代码。

对于进程句柄,您需要一个IntPtr来保存句柄。 所以你需要这样的东西:

 IntPtr hProcess //previously retrieved. IntPtr lpAttributeList //previously allocated using InitializeProcThreadAttributeList and Marshal.AllocHGlobal. const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000; IntPtr lpValue = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValue, hProcess); if(UpdateProcThreadAttribute(lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValue, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero)) { //do something } //Free lpValue only after the lpAttributeList is deleted.