title: C# Convert IntPtr into int
body: <p>I am dynamically calling Windows API. I found some code online that can do this, and I took a whole lot of interest to it. The idea itself is brilliant to say the least. However, I can't seem to make it work for my code. The parameters for the dynamic call are as of type <code>string</code>, <code>string</code> <code>int[]</code>, and I would like to use the API <code>GetThreadContext</code> with the parameters of <code>pInfo.hThred</code> and <code>ref ctx</code> (shown below).</p>
  
  <p><strong>API Call</strong></p>
  
  <pre><code>GetThreadContext(pInfo.hThread, ref ctx);
  </code></pre>
  
  <p>The above code will make a call to the GetThreadContext API (given that it is declared in my project) - and works perfectly fine. The beauty of the dynamic call, however, is that no declaration is needed. So, my attempt at the dynamic call:</p>
  
  <pre><code>ctx = new CONTEXT {ContextFlags = 0x10007};
  PROCESS_INFORMATION pInfo;
  
  CInvokeAPI.Invoke("kernel32","GetThreadContext",pInfo.hThread, ctx);
  </code></pre>
  
  <p>The issue here is that I haven't a clue as to how I can pass parameter ctx as type int given the fact that it is a struct.</p>
  
  <p><strong>Please see below for additional code</strong></p>
  
  <pre><code>    [StructLayout(LayoutKind.Sequential)]
      struct CONTEXT
      {
          public uint ContextFlags;
          unsafe fixed byte unused[160];
          public uint Ebx;
          public uint Edx;
          public uint Ecx;
          public uint Eax;
          unsafe fixed byte unused2[24];
      }
  
      [StructLayout(LayoutKind.Sequential)]
      struct PROCESS_INFORMATION
      {
          public IntPtr hProcess;
          public IntPtr hThread;
          public int dwProcessId;
          public int dwThreadId;
      }
  </code></pre>
  
  <p><strong>Call API Dynamically Class</strong></p>
  
  <pre><code>using System;
  using System.Runtime.InteropServices;
  using System.Text;
  
  /* 
   * Title: CInvokeAPI.cs
   * Description: Call API by name implementation in purely managed C# (no 'unsafe' mess here).
   * 
   * Developed by: affixiate 
   * Comments: If you use this code, I require you to give me credits. 
   */
  
  public static class CInvokeAPI
  {
      /// &lt;summary&gt;
      /// Generates a new, non-garbage collectable string in memory. Use this with Unicode "W" API.
      /// &lt;/summary&gt;
      /// &lt;param name="theString"&gt;A Unicode string.&lt;/param&gt;
      /// &lt;returns&gt;Address of newly allocated string in memory. Remember to free it after use.&lt;/returns&gt;
      public static int StringToPtrW(string theString)
      {
          return StringToPtr(Encoding.Unicode.GetBytes(theString));
      }
  
      /// &lt;summary&gt;
      /// Generates a new, non-garbage collectable string in memory. Use this with ANSI "A" API.
      /// &lt;/summary&gt;
      /// &lt;param name="theString"&gt;An ANSII string.&lt;/param&gt;
      /// &lt;returns&gt;Address of newly allocated string in memory. Remember to free it after use.&lt;/returns&gt;
      public static int StringToPtrA(string theString)
      {
          return StringToPtr(Encoding.ASCII.GetBytes(theString));
      }
  
      /// &lt;summary&gt;
      /// Internal method used to allocate memory.
      /// &lt;/summary&gt;
      /// &lt;param name="buf"&gt;A byte buffer.&lt;/param&gt;
      /// &lt;returns&gt;Address of newly allocated memory. Remember to free it after use.&lt;/returns&gt;
      private static int StringToPtr(byte[] buf)
      {
          return (int)GCHandle.Alloc(buf, GCHandleType.Pinned).AddrOfPinnedObject();
      }
  
      /// &lt;summary&gt;
      /// Invokes the specified Windows API.
      /// &lt;/summary&gt;
      /// &lt;param name="libraryName"&gt;Name of the library.&lt;/param&gt;
      /// &lt;param name="functionName"&gt;Name of the function.&lt;/param&gt;
      /// &lt;param name="args"&gt;The arguments.&lt;/param&gt;
      /// &lt;returns&gt;True if function succeeds, otherwise false.&lt;/returns&gt;
      public static bool Invoke(string libraryName, string functionName, params int[] args)
      {
          /* Sanity checks. */
          IntPtr hLoadLibrary = LoadLibrary(libraryName);
          if (hLoadLibrary == IntPtr.Zero) return false;
  
          IntPtr hGetProcAddress = GetProcAddress(hLoadLibrary, functionName);
          if (hGetProcAddress == IntPtr.Zero) return false;
  
          // Allocates more than enough  memory for an stdcall and the parameters of a WinAPI function
          IntPtr hMemory = VirtualAlloc(IntPtr.Zero, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, MEM_EXECUTE_READWRITE);
          if (hMemory == IntPtr.Zero)
              return false;
  
          IntPtr hMemoryItr = hMemory;
  
          // Prepends the stdcall header signature
          Marshal.Copy(new byte[] {0x55, 0x89, 0xE5}, 0, hMemoryItr, 0x3);
          hMemoryItr = (IntPtr)((int)hMemoryItr + 0x3);
  
          // Loop through the passed in arguments and place them on the stack in reverse order
          for (int i = (args.Length - 1); i &gt;= 0; i--) 
          {
              Marshal.Copy(new byte[] {0x68}, 0, hMemoryItr, 0x1); 
              hMemoryItr = (IntPtr)((int)hMemoryItr + 0x1);
              Marshal.Copy(BitConverter.GetBytes(args[i]), 0, hMemoryItr, 0x4);
              hMemoryItr = (IntPtr)((int)hMemoryItr + 0x4);
          }
  
          Marshal.Copy(new byte[] {0xE8}, 0, hMemoryItr, 0x1);
          hMemoryItr = (IntPtr)((int)hMemoryItr + 0x1);
          Marshal.Copy(BitConverter.GetBytes((int)hGetProcAddress - (int)hMemoryItr - 0x4), 0, hMemoryItr, 0x4);
          hMemoryItr = (IntPtr)((int)hMemoryItr + 0x4);
  
          // Cleaning up the stack
          Marshal.Copy(new byte[] {0x5D, 0xC2, 0x4, 0x0 /* &lt;= I made a LOL. */}, 0, hMemoryItr, 0x4);
          // Don't forget to increment if you are adding more ASM code here: hMemoryItr = (IntPtr)((int)hMemoryItr + 0x4);
  
          try
          {
              var executeAsm = (RunAsm) Marshal.GetDelegateForFunctionPointer(hMemory, typeof (RunAsm));
              executeAsm();
          }
          catch { return false; }
  
          // Clean up the memory we allocated to do the dirty work
          VirtualFree(hMemory, 0, MEM_RELEASE);
          return true;
      }
  
      // ReSharper disable InconsistentNaming
      private const uint MEM_RELEASE = 0x8000;
      private const uint MEM_COMMIT = 0x1000;
      private const uint MEM_RESERVE = 0x2000;
      private const uint MEM_EXECUTE_READWRITE = 0x40;
      // ReSharper restore InconsistentNaming
  
      // My own sexy delegate:
      [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
      private delegate void RunAsm();
  
      // WinAPI used:
      [DllImport("kernel32.dll", SetLastError = true)]
      private static extern bool VirtualFree(IntPtr lpAddress, UInt32 dwSize, uint dwFreeType);
  
      [DllImport("kernel32.dll", SetLastError = true)]
      private static extern IntPtr VirtualAlloc(IntPtr lpAddress, UInt32 dwSize, uint flAllocationType, uint flProtect);
  
      [DllImport("kernel32.dll", SetLastError = true)]
      private static extern IntPtr LoadLibrary(string lpFileName);
  
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
      private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
  }
  </code></pre>