How to: Define the Scope of Pinning Pointers
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

How to: Define the Scope of Pinning Pointers

An object is pinned only while a pin_ptr points to it. The object is no longer pinned when its pinning pointer goes out of scope, or is set to nullptr. After the pin_ptr goes out of scope, the object that was pinned can be moved in the heap by the garbage collector. Any native pointers that still point to the object will not be updated, and dereferencing one of them could raise an unrecoverable exception.


// pin_ptr_scope.cpp
// compile with: /clr
ref class G {
   int i;

int * f(G ^ hG) {
   pin_ptr<int> ppi = &(hG->i);
   int * i = ppi;
   return i;

int main() {
   G ^ MyG = gcnew G;
   int * i;
   i = f(MyG);   // bad!  object that i points to is no longer pinned

See Also



© 2016 Microsoft