此代码工作正常,可以多次调用,没有任何问题。 但是,如果位图调整大小(制作得更大),则会出现访问冲突。 如果bimap变小,情况就不是这样。C#内存访问冲突
我可以一直确认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
我可能在这里有点厚。你指的是第三个参数?如果它是ViewFile,这将改变每个循环,因为我正在清理(为false)FileMappingCreated。 – user183185 2009-10-15 09:41:52
“如果它是ViewFile,这将改变每个循环” - 不,它不会。在调试器中检查句柄。 – ima 2009-10-15 10:48:36
对不起,忘了补充说,所有的变量随着调整大小而改变,因此,Marshal.Copy中的变量也是如此。在这种情况下,它不会保持原始大小和错误,因为它会超过第一次运行时设置的大小。 – user183185 2009-10-15 12:09:38