How to correctly pin objects for GC in c# to prevent AccessViolationException?

192 Views Asked by At

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?

0

There are 0 best solutions below