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

时间:2014-07-04 21:31:43

标签: c# emgucv intptr opencvsharp

我正在使用.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

不幸的是,我在方法'复制'中存在访问冲突异常!我不明白为什么。

有人可以帮助我吗?

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您可以在不安全的环境中投放IntPtrvoid*。你可以这样做:

unsafe
{
    var bytePtr = (byte*)(void*)buffer;

    // Here use *bytePtr to get the byte value at bytePtr, just like in C/C++
}

答案 1 :(得分:0)

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

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