title: Access Violation Exception using the method Marshal.Copy()
body: <p>I'm writing a simple OpenCV application using .NET which the goal is to render the webcam stream on a simple window.</p>
  
  <p>Here's the code I use to do this:</p>
  
  <pre><code>private static BitmapSource ToBitmapSource(IImage image)
  {
      using (System.Drawing.Bitmap source = image.Bitmap)
      {
          IntPtr ptr = source.GetHbitmap();
          BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
              ptr,
              IntPtr.Zero,
              Int32Rect.Empty,
              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
          DeleteObject(ptr);
          return bs;
      }
  }
  
  private void CameraShow()
  {
      ImageViewer viewer = new Emgu.CV.UI.ImageViewer(); //create an image viewer
      Capture capture = new Capture(); //create a camera captue
  
      this.isCamOff = false;
      while (this.CamStat != eCamRun.CamStop)
      {
          Thread.Sleep(60);
          viewer.Image = capture.QueryFrame(); //draw the image obtained from camera
          System.Windows.Application.Current.Dispatcher.Invoke(
              DispatcherPriority.Normal,
              (ThreadStart)delegate
          {
              this.ImageStream.Source = ToBitmapSource(viewer.Image); //BitmapSource
          });
      }
  
      viewer.Dispose();
      capture.Dispose();
      this.isCamOff = true;
      Thread.CurrentThread.Interrupt();
  }
  </code></pre>
  
  <p>But now I want to display on the console the content of the pixel buffer contained into the System.Drawing.Bitmap object (I know the void* native type is contained into the IntPtr variable into the Bitmap object). So according to my source code just below to recover the IntPtr variable I have to write the following line of code (into an 'unsafe' context):</p>
  
  <pre><code>IntPtr buffer = viewer.Image.Bitmap.GetHbitmap();
  
  byte[] pPixelBuffer = new byte[16]; //16 bytes allocation
  Marshal.Copy(buffer, pPixelBuffer, 0, 9); //I copy the 9 first bytes into pPixelBuffer
  </code></pre>
  
  <p>Unfortunately, I have an Access Violation Exception into the method 'Copy'! And I don't understand why.</p>
  
  <p>Does anyone can help me, please ?</p>
  
  <p>Thanks a lot in advance for your help.</p>