title: void ** handles with P/Invoke
body: <p>I am using a C API DLL from a 3rd party vendor.  The problem I have is that I can't seem to find a good template for Marshalling the following C code:</p>
  
  <pre><code>API_Open( void ** handle );
  API_Close( void * handle );
  </code></pre>
  
  <p>The calls are simplified, but the handle is a void *, which is (in C) passed into the <code>API_Open</code> call as &amp;handle, and then passed into <code>API_Close</code> as handle.</p>
  
  <p>I've tried to do the same in C#, but can't figure out how to Marshal handle properly.  My C# version (latest try) is:</p>
  
  <pre><code>[DllImport("External.dll",EntryPoint="API_Open")]
  public static extern int API_Open( out IntPtr handle );
  [DllImport("External.dll",EntryPoint="API_Close")]
  public static extern int API_Close( IntPtr handle );
  
  public static int Wrapper_API_Open( ref Int32 handle )
  {
      int rc = SUCCESS;
  
      // Get a 32bit region to act as our void**
      IntPtr voidptrptr = Marshal.AllocHGlobal(sizeof(Int32));
  
      // Call our function.  
      rc = API_Open(out voidptrptr);
  
      // In theory, the value that voidptrptr points to should be the 
      // RAM address of our handle.
      handle = Marshal.ReadInt32( Marshal.ReadIntPtr(voidptrptr) );
  
      return rc;
  }
  
  public static int Wrapper_API_Close(ref Int32 handle)
  {
      int rc = SUCCESS;
  
      // Get a 32bit region to act as our void *
      IntPtr voidptr = Marshal.AllocHGlobal(sizeof(Int32));
  
      // Write the handle into it.
      Marshal.WriteInt32(voidptr,handle);
  
      // Call our function.
      rc = API_Close(voidptr);
  
      return rc;
  }
  
  
  public void SomeRandomDrivingFunction()
  {
      .
      .
      .
      Int32 handle;
      Wrapper_API_Open( ref handle );
      .
      .
      .
      Wrapper_API_Close( ref handle );
      .
      .
      .
  }
  </code></pre>
  
  <p>The API return code is always INVALID_DEVICE_OBJECT when I call API_Close.  Any thoughts?  I thought this would be pretty straightforward, but I'm having trouble wrapping my head around the void** and void* parts of the function calls.  </p>
  
  <p>Thanks</p>