Reputation:
Let's say we want to pass a managed String object to a Win32 function and I just pass IntPtr
of this string object to the native function, but before the native function uses the address of passed string object, the garbage collector collects the string object because there is no root to reference the string object in the managed code any more.
My question is, does Garbage Collector set the reference of string object to null or leave it untouched so the referenc might point to sth else? if it is former, the native function can do a null check, if it is the latter, then native function can do nothing about it and might touch sth it shouldn't touch.
Upvotes: 0
Views: 222
Reputation: 36774
The GC tracks references to managed objects. An IntPtr
is not a reference to a managed object, it is just an arbitrary value. It is therefore invisible to the GC and cannot be updated, since the GC does not know if it points to a managed object, some unmanaged memory, or something else entirely. If the GC did somehow know that it pointed to a managed object it could treat it as any other managed reference and avoid collecting the object in the first place.
I believe that anytime you use an pointer to managed memory you need to use pinning to ensure that the object is not collected or moved.
There is also Gc.KeepAlive to ensure objects owning unmanaged resources have a lifetime longer than the usage of said resources. Say an object owning umanaged memory and a finalizer that releases said memory. You could take a pointer to the unmanaged memory, and if it was the last usage of the object, the finalizer of the object could be called, releasing the memory.
Upvotes: 1