C#内存访问冲突

时间:2009-10-15 08:50:56

标签: c#-2.0

此代码工作正常,可以多次调用,没有任何问题。 但是,如果调整位图大小(变大),我会收到访问冲突。 如果bimap变小,情况就不是这样了。

我可以确认BMPSize& BitmapBytes数组大小始终为。

有人可以对此传播任何信息吗?

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,
                    IntPtr.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;
    }

非常感谢所有人。

PyroPaul

2 个答案:

答案 0 :(得分:1)

据我所知,位图大小也受显卡的功能限制。我们通常不会超过大于1024 x 1024px的任何纹理/位图大小。如果您的位图大于此大小,则会出现一些奇怪的错误。

你的位图有多大?尝试将其切成碎片以逐片装载。

答案 1 :(得分:0)

  

可以确认BMPSize&amp;   BitmapBytes数组大小统计   次。

这是三个参数中的两个。

相关问题