# Wednesday, 29 November 2006

To follow up on my post about pinning pointers, let me ask one of those tricky questions that someone asked me. If I have an array of things, how do I pin the whole thing? If I ask for a pinning pointer based on element #3 of the array, can I use pointer arithmetic from that pinned pointer to reach elements #4 through #11? Do I have to pin each element one at a time?

The answer is that pinning any element of an array pins the whole array, and that once you have a pinned pointer to one element of the array you can do the usual pointer things. This includes not only incrementing it to move through the array, but if it's a char* you can pass it to things that expect strings and those things will never know the difference. Here's an example from MSDN:

array<Byte>^ arr = gcnew array<Byte>(4);
arr[0] = 'C';
arr[1] = '+';
arr[2] = '+';
arr[3] = '\0';
pin_ptr<Byte> p = &arr[1];   // entire array is now pinned
unsigned char * cp = p;
printf_s("%s\n", cp); // bytes pointed at by cp will not move during call

This sample prints out ++.

Kate

Wednesday, 29 November 2006 08:42:29 (Eastern Standard Time, UTC-05:00)  #    Comments [0]
Comments are closed.