次の方法で共有


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.

Example

// pin_ptr_scope.cpp
// compile with: /clr
ref class G {
public:
   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

Concepts

pin_ptr