title: Copying byte array with Marshal.Copy from IntPtr using C# doesn't work
body: <p>I'm using an unmanaged library, which generates grayscale images (about 100x200 pixels, more or less). An image is contained within a struct, which looks like this in C:</p>
  
  <pre><code>typedef struct abs_image {
      ABS_DWORD Width;
      ABS_DWORD Height;
      ABS_DWORD ColorCount;
      ABS_DWORD HorizontalDPI;
      ABS_DWORD VerticalDPI;
      ABS_BYTE ImageData[ABS_VARLEN];
  } ABS_IMAGE
  </code></pre>
  
  
  
  <pre><code>typedef unsigned int     ABS_DWORD;
  typedef unsigned char     ABS_BYTE;
  </code></pre>
  
  <p>And here my C# wrapper struct:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
  public struct ABS_IMAGE {
      public uint Width;
      public uint Height;
      public uint ColorCount;
      public uint HorizontalDPI;
      public uint VerticalDPI;
      public IntPtr ImageData;
  }
  </code></pre>
  
  <p>Grabbing the image and marshallign the <code>ABS_IMAGE</code> struct works just fine. In a previous version, I tried using a byte array with fixed length for ImageData, which crashed sometimes. This happened, I think, because the image size is not fix.
  Now I try to read the image byte array at later time, when I can calulate the real array length before. Here the relevant code:</p>
  
  <pre><code>ABS_Type_Defs.ABS_IMAGE img =
      (ABS_Type_Defs.ABS_IMAGE)Marshal.PtrToStructure(
      pImage,
      typeof(ABS_Type_Defs.ABS_IMAGE));
  
  int length = ((int)img.Height - 1) * ((int)img.Width - 1);
  byte[] data = new byte[length];
  
  Marshal.Copy(img.ImageData, data, 0, length);
  </code></pre>
  
  <p>Now my problem: Every time I want to execute Marshal.Copy to read the image bytes, I get an <code>AccessViolationException</code>.</p>
  
  <p>Does anyone have an idea?</p>