Tip 92 of #TuesdayCodingTips - Pinning interop memory in C#
When interoping C# with, for example, C++, one can send a pointer to the managed memory directly to the native code and work with it without the need to copy it into the local address space. For as long as the code operates within a single process, the memory space is shared.
However, there is a gotcha you need to keep in mind. First, you need to ensure that the garbage collector won’t delete that memory by keeping it referenced in the managed code. Second, even if you do, GC might decide to reorganize the memory around to reduce fragmentation and improve allocation times.
You can prevent this behavior on a particular pointer by protecting it with a “pinned” GC allocation — technically not allocating new memory, but rather protecting existing memory from being shuffled around.
Just remember to "free" the pointer once it is no longer used in native code, so the memory can be reused for something else.
