An object or sub-object of a managed class can be pinned, in which case the common language runtime will not move it during garbage collection. The principal use of this is to pass a pointer to managed data as an actual parameter of an unmanaged function call. During a collection cycle, the runtime will inspect the metadata created for the pinning pointer and will not move the item it points to.
Pinning a sub-object defined in a managed object has the effect of pinning the entire object.
If the pinning pointer is reassigned to point to a new value, the previous instance pointed to is no longer considered pinned.
When a pinning pointer goes out of scope, the object is no longer considered pinned, unless there are other pinning pointers pointing to or into the object. You do not have to explicitly unpin a pointer.
If no pinning pointers point to the object (all pinning pointers went out of scope, were reassigned to point to other objects, or were assigned nullptr), the object is guaranteed not to be pinned.
A pinning pointer can point to a reference handle, value type or boxed type handle, member of a managed type or to an element of a managed array. It cannot point to a reference type.
Note: |
|---|
Taking the address of a pin_ptr that points to a native object results in undefined behavior. |
Pinning pointers can only be declared as non-static local variables on the stack.
Pinning pointers cannot be used as:
A pin_ptr represents a superset of the functionality of a native pointer. Therefore, anything that can be assigned to a native pointer can also be assigned to a pin_ptr. An interior pointer is permitted to perform the same set of operations as native pointers, including comparison and pointer arithmetic.
pin_ptr is in the cli namespace. See cli Namespace for more information.
For information about interior pointers, see interior_ptr.
For information about pinning pointers, see