title: AccessViolationException in PInvoke function call
body: <p>I'm trying to write a wrapper for C library but I'm really struggling with this error. </p>
  
  <p>I tried many approaches, here is one of them:</p>
  
  <pre><code>    [DllImport(DRIVER_FILENAME)]
      [return: MarshalAs(UnmanagedType.U4)]
      private static extern uint GetData(IntPtr handle,
          [MarshalAs(UnmanagedType.LPArray), In()] int[] buffer,
          [MarshalAs(UnmanagedType.U4)] uint size);
  </code></pre>
  
  <p>Here is function <em>GetData</em> from the library documentation:</p>
  
  <pre><code>LONG GetData( 
    IN HANDLE Handle,
    OUT PULONG Buffer, 
    IN ULONG Size
  ); 
  </code></pre>
  
  <p>Function returns continuous data (about 16KB/s) in buffer which size is given in bytes. <em>Buffer</em> is <em>int[16384]</em>. My code looks like this:</p>
  
  <pre><code>public static uint GetLibData(IntPtr handle, int[] buffer, uint size)
      {
          size *= 4;            
          uint sizeRead = GetData(handle, buffer, size);
  
          sizeRead /= 4;
  
          return sizeRead;
      }
  </code></pre>
  
  <p>Problematic argument is <em>buffer</em>, I tried manage it previously in other ways, such as <em>IntPtr bufferPtr</em> and then allocating memory by <em>Marshal.AllocHGlobal</em> but I was getting the same error:</p>
  
  <blockquote>
    <p>Attempted to read or write protected memory. This is often an
    indication that other memory is corrupt.</p>
  </blockquote>
  
  <p>How to correctly invoke this function?</p>