使用方法Marshal.Copy()的访问冲突异常



我正在使用。net编写一个简单的OpenCV应用程序,其目标是在一个简单的窗口上呈现网络摄像头流。

下面是我用来做这件事的代码:
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();
}

但是现在我想在控制台显示包含在System.Drawing.Bitmap对象中的像素缓冲区的内容(我知道void* native类型包含在Bitmap对象的IntPtr变量中)。因此,根据下面我的源代码来恢复IntPtr变量,我必须编写以下代码行(进入"不安全"的上下文中):

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

不幸的是,我有一个访问冲突异常到方法'Copy'!我不明白为什么。

请问有人能帮我吗?

事先非常感谢您的帮助

可以在不安全的上下文中将IntPtr强制转换为void*。所以你可以这样做:

unsafe
{
    var bytePtr = (byte*)(void*)buffer;
    // Here use *bytePtr to get the byte value at bytePtr, just like in C/C++
}

如何使用Marshal.Copy ?这样,您就可以将IntPtr的内容复制到byte[],而无需进入unsafe

http://msdn.microsoft.com/en-us/library/ms146631 (v = vs.110) . aspx

最新更新