I'm doing some image manipulation in .NET (VB 2010). I'm using the following code (which doesn't do anything yet):
Sub Manipulate(IMG As Bitmap)
' Dim foo(100000) As Integer - will need it later...
Dim bd = IMG.LockBits(New Rectangle(0, 0, IMG.Width, IMG.Height),
Imaging.ImageLockMode.ReadWrite,
Imaging.PixelFormat.Format24bppRgb)
Dim absstride = Math.Abs(bd.Stride)
Dim numbytes = absstride * IMG.Height
Dim bytes(numbytes - 1) As Byte
Dim flipped = bd.Stride < 0
Dim ptr = If(flipped, bd.Scan0 - numbytes + absstride, bd.Scan0)
System.Runtime.InteropServices.Marshal.Copy(ptr, bytes, 0, numbytes)
' I'm going to put sg here
System.Runtime.InteropServices.Marshal.Copy(bytes, 0, ptr, numbytes)
IMG.UnlockBits(bd)
End Sub
This works perfectly for simple purposes (eg. brightening the image), but my algorithm needs some big variables (see 'foo' above). When declaring it (uncomment that line), I suddenly get exceptions:
depending on the size of 'foo'...
...either the first Marshal.Copy() throws
AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
...or the declaration of 'bytes' throws
FatalExecutionEngineError: The runtime has encountered a fatal error. The address of the error was at 0x6819d142, on thread 0x3690. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
...or no exceptions at all and everything works fine.
What is going on?
Additional info: I get the image objects from webcam using DirectShow.
As Hans pointed out, I have to make a deep copy of the bitmap and everything works. Otherwise I'm using an image that is already disposed. This is a silent error though, until I declare some big variables, which use up the disposed memory, that's when the GC throws some seemingly random errors.