0

I need to pin the Scan0 of a very small Bitmap Image. By doing so I want to prevent the GC moving it in the memory. I use some native methods which use the IntPtr Scan0 and when the GC supposedly moves the Bitmap, I get a System.AccessViolationException.

I have found the following methods to accomplish that:

  1. Using GCHandle: When I use a GCHandle I can allocate Memory to be pinned. I have to free the memory myself.

  2. Using the fixed Statement: When I use the fixed statement I can only use the pinned object inside the following block, which is impractical for me in this case.

  3. Using the stackalloc expression: I have not found a way to use stackalloc with an IntPtr.

Are my assumptions correct so far?

Are there other practices to pin an IntPtr to memory?

  • You are hitting AVE probably due to other memory access bug rather than the GC moving the bitmap - reading the byte data out of range or something? [Bitmap is a wrapper around already unmanaged GDI+ data](https://stackoverflow.com/questions/15183958/does-bitmap-lockbits-pin-a-bitmap-into-memory), no need to pin it in the range of `LockBits`/`UnlockBits`. – Konrad Kokosa Mar 16 '21 at 11:56
  • @KonradKokosa If I hit the AVE in some third party code I can do nothing about it. I am not only working inside LockBits but I instanciate an OpenCV Mat with the Scan0 IntPtr. I unlock the bits right after and go on to work with the Mat. I can not clone the Bitmap because it is a very time sensitive application. – Simon Tendick Mar 16 '21 at 12:29
  • *"I unlock the bits right after and go on to work with the Mat"* - but how then Mat operates on the data? `LockBits` is a wrapper for `GdipBitmapLockBits` which [*"provides a temporary buffer that you can use to read or write pixel data in a specified format"*](https://docs.microsoft.com/en-us/windows/win32/gdiplus/-gdiplus-bitmap-flat), and this is the one represented by `IntPtr`. And because *"Any pixel data that you write to the buffer is copied to the Bitmap object when you call `Bitmap::UnlockBits`"*, this buffer (and thus `IntPtr` used by your Mat), does not make sense after unlocking. – Konrad Kokosa Mar 16 '21 at 13:25

0 Answers0