Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
How to: Define the Scope of Pinning Pointers

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



Community Additions

© 2015 Microsoft