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:
Using GCHandle: When I use a GCHandle I can allocate Memory to be pinned. I have to free the memory myself.
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.
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?