Sunday, June 11, 2006

Pinning Pointers

Consider this situation: You have a well written tested native function which expects an array. You want to pass an managed array to the function. How would you do that? Think... Whatever your ideas are here's a cool way to do that in the new C++/CLI syntax. Use Pin Pointers

Before we understand how to use pin pointers lets give a thought on why cant a native pointer point to a managed location. An easy question. The simple answer to this is if it was allowed then it would work fairly smooth only till GC throws itself into action. During GC cycle compaction of the heap takes place. The pointer now points to some other data even though the location is same.

So it is not allowed for a native pointer to point to a location in the Managed heap. What if there was a way by which we can avoid relocation of the data during GC cycle. In that case our problem would get solved. Here pinning pointers come into picture.


pin_ptr ppC = &arr[0]; //implicit conversion from interior to pin pointer


Now the location of this array wont change in the Managed Heap.

Caution: Creating pin_ptrs interfere with the working of garbage collector. Use them carefully. You should try to allocate them in such a way that they remain in older generations of the Managed heap.

No comments: