我正在尝试在Windows 7上 PInvoke UpdateProcThreadAttribute()但我的尝试只是在最后Win32错误为50时继续返回FALSE。

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。

我将使用的声明是:

    [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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top