GCHandle
when a managed object holds the pointer of (address of) an unmanaged object, life is simple. because Garbage collector keeps shifting the managed objects here and there ( between generations.)
But that managed object keeps the address of unmanaged variable as is.
Now what if we have a situation where the unmanaged objects holds the address of managed object, so the garbage cleaning process keeps relocating the managed object...
Wait... We can ask GC to not touch this variable (managed object) even during GC.
So here goes..
string mystring = "someobject";
byte[] stringinbyte = ASCIIEncoding.ASCII.GetBytes(mystring);
// Pin down our managed object
GCHandle handle = GCHandle.Alloc(stringinbyte, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();
// Let the unmanaged object complete its work
// ....
handle.Free();
remember this GCHandle is specific to this appdomain.