开发者

C# Memory Access Violation

This code works fine and can be called numerous times without any problems. However, if the bitmap is resized (made bigger), I get an access violation. This is not the case if the bimap is made smaller.

I can confirm that the BMPSize & BitmapBytes array size tally at all times.

Can anyone spread any light on this, please?

public void SetBitmap(Bitmap bmp)
    {
        UInt32 BMPSize = Convert.ToUInt32(bmp.Height * bmp.Width * 4);
        BMPSize += 0x36;

        if (!FileMappingCreated)
        {
            MemoryFileHandle = CreateFileMapping((IntPtr)0, (IntPtr)0,
                PageProtection.ReadWrite, 0, BMPSize, SharedName);

            if (MemoryFileHandle != null)
            {
                SetNamedSecurityInfo(SharedName, SE_OBJECT_TYPE.SE_KERNEL_OBJECT, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION,
                    In开发者_StackOverflow中文版tPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);


                ViewFile = MapViewOfFile(MemoryFileHandle, FILE_MAP_WRITE, 0, 0, 0);


                if (MemoryFileHandle == IntPtr.Zero)
                {
                    CloseHandle(MemoryFileHandle);
                }
                else
                {
                    FileMappingCreated = true;
                }
            }
        }

        MemoryStream stream = new MemoryStream();          

        bmp.Save(stream, ImageFormat.Bmp);

        byte[] BitmapBytes = stream.ToArray();

        // BMP SIZE Value 4bytes long see internet for DIB structure.
        byte[] DIBImageSize = null;
        int ImageSizeAddress = 0x22;

        DIBImageSize = BitConverter.GetBytes(Convert.ToInt32(BMPSize)); 

        // put DIBImageSize into array starting at address 0x22
        for (int i = 0; i < DIBImageSize.Length; i++)
        {
            BitmapBytes[ImageSizeAddress] = DIBImageSize[i];
            ImageSizeAddress++;
        }   

        // THIS IS THE LINE THAT FAILS  
       Marshal.Copy(BitmapBytes, 0, ViewFile, Convert.ToInt32(BMPSize));           

        BitmapBytes = null;
        DIBImageSize = null;
        FileMappingCreated = false;
    }

Many thanks to all.

PyroPaul


As I know, the bitmap size is also limited by the capability of the display card. We normally do not exceed any texture/ bitmap size larger than 1024 x 1024px. Some strange errors will occur if your bitmap is larger than this size.

How big is your Bitmap? Try to cut it into pieces to load it piece by piece.


can confirm that the BMPSize & BitmapBytes array size tally at all times.

That's two out of three parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜