使用 Marshal.ReadByte() 时出现 AccessViolationException

问题描述 投票:0回答:0

我正在尝试将 Halcon 对象转换为位图,并在网上找到了这段代码: https://github.com/Joncash/HanboAOMClassLibrary/blob/master/Hanbo.Helper/ImageConventer.cs

/// <summary>
/// Halcon Image .NET Bitmap
/// </summary>
/// <param name="halconImage"></param>
/// <returns></returns>
public static Bitmap ConvertHalconImageToBitmap(HObject halconImage, bool isColor)
{
    if (halconImage == null)
    {
        throw new ArgumentNullException("halconImage");
    }

    HTuple pointerRed = null;
    HTuple pointerGreen = null;
    HTuple pointerBlue = null;
    HTuple type;
    HTuple width;
    HTuple height;

    // Halcon
    var pixelFormat = (isColor) ? PixelFormat.Format32bppRgb : PixelFormat.Format8bppIndexed;
    if (isColor)
        HOperatorSet.GetImagePointer3(halconImage, out pointerRed, out pointerGreen, out pointerBlue, out type, out width, out height);
    else
        HOperatorSet.GetImagePointer1(halconImage, out pointerBlue, out type, out width, out height);


    Bitmap bitmap = new Bitmap((Int32)width, (Int32)height, pixelFormat);

    BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
    int bytes = Math.Abs(bmpData.Stride) * bitmap.Height;
    byte[] rgbValues = new byte[bytes];


    IntPtr ptrB = new IntPtr(pointerBlue);
    IntPtr ptrG = IntPtr.Zero;
    IntPtr ptrR = IntPtr.Zero;
    if (pointerGreen != null) ptrG = new IntPtr(pointerGreen);
    if (pointerRed != null) ptrR = new IntPtr(pointerRed);


    int channels = (isColor) ? 3 : 1;

    // Stride
    int strideTotal = Math.Abs(bmpData.Stride);
    int unmapByes = strideTotal - ((int)width * channels);
    for (int i = 0, offset = 0; i < bytes; i += channels, offset++)
    {
        if ((offset + 1) % width == 0)
        {
            i += unmapByes;
        }

        rgbValues[i] = Marshal.ReadByte(ptrB, offset); //where I get the accesviolation
        if (isColor)
        {
            rgbValues[i + 1] = Marshal.ReadByte(ptrG, offset);
            rgbValues[i + 2] = Marshal.ReadByte(ptrR, offset);
        }

    }

    Marshal.Copy(rgbValues, 0, bmpData.Scan0, bytes);
    bitmap.UnlockBits(bmpData);
    return bitmap;
}

但是当我尝试运行它时,它在读取或写入受保护的内存时得到一个 AccesViolationExeption。 有人知道为什么吗?

我已经调试并确保 IntPtr 不为空

c# memory marshalling access-violation halcon
© www.soinside.com 2019 - 2024. All rights reserved.