A Code Snippet Before The Weekend


Just a quick post for today.  I needed to use the LPPROCESS_INFORMATION C type from managed code today, so I poped over to PInvoke.net to see if there was any information on it.  There was a definition for PROCESS_INFORMATION, but nothing on LPPROCESS_INFORMATION (well, yes there is now … but that’s because I put it there 🙂  ).


Anyway, here’s a quick snippet on going from PROCESS_INFORMATION to LPPROCESS_INFORMATION in managed code.  (Since I don’t like capitals and underscores in my C#, I’ve renamed PROCESS_INFORMATION to ProcessInformation).  Next week I’ll blog more about why I needed this.



[StructLayout(LayoutKind.Sequential)]
public struct ProcessInformation
{
    public IntPtr hProcess;
    public IntPtr hThread;
    public uint dwProcessId;
    public uint dwThreadId;


ProcessInformation procInfo = new ProcessInformation();
GCHandle procInfoHandle = GCHandle.Alloc(procInfo, GCHandleType.Pinned);
         
try
{
    IntPtr lpprocessInformation = procInfoHandle.AddrOfPinnedObject();
    // … code that needs to use the LPPROCESS_INFORMATION …
}
finally
{
    procInfoHandle.Free();
}        


Note that you can’t use the C# using construct with a GCHandle, since GCHandles do not implement IDisposable, so you need to use a try … finally construct.

Comments (2)

  1. Pavel Lebedinsky says:

    When is this actually needed? For APIs like CreateProcessXxx that take a LPPROCESS_INFORMATION, something like this seems to work for me:

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]

    static extern bool CreateProcessWithLogonW(



    ref STARTUPINFO startupInfo,

    out PROCESS_INFORMATION processInfo

    );

  2. Shawn says:

    I didn’t want to use out since the LPPROCESS_INFORMATION wasn’t really the "output" of the function call. I know that out isn’t reserved for output parameters only, but I do like to keep those semantics. (Though I suppose you could make an argument for ref in this case).

    -Shawn