I have the following code to allocate buffer
uns16 m_rawBuffer = new uns16[m_rawBufferSize]; pin_ptr<uns16> ptrAcqBuffer = m_rawBuffer;
Although it is pin_ptr from time to time GC modifies ptrAcqBuffer.
<a href="https://msdn.microsoft.com/en-us/library/1dz8byfh.aspx" rel="nofollow">From the document</a> I see<blockquote>
A pinning pointer is an interior pointer that prevents the object pointed to from moving on the garbage-collected heap. That is, the value of a pinning pointer is not changed by the common language runtime. This is required when you pass the address of a managed class to an unmanaged function so that the address will not change unexpectedly during resolution of the unmanaged function call.</blockquote>
It doesn't make sesnse to me... Can someone please explain ? Also because I created m_rawBuffer with "new" do I need to "pin_ptr" ?
The garbage collector moves all of the objects on the managed heap whenever it does a garbage collection. This is part of its normal operation. This is why a 'regular' pointer to a managed object isn't valid, because it can be moved at any time by the garbage collector.
A pin pointer marks the object on the managed heap as "don't move me!", so the pointer remains valid as long as the
pin_ptr object exists. You can then pass the pin pointer to methods that expect a regular raw pointer, and the object that it's pointing at won't move until the
pin_ptr object is destroyed.
All of this has to do with the managed heap. Assuming the code fragment you showed was C++/CLI code, you're using
new to allocate an array on the regular <em>unmanaged</em> heap. Pinning is not necessary, it will not move on its own.
If you had done
array<UInt16>^ buffer = gcnew array<UInt16>(m_rawBufferSize);, then you would need the pin.
...from time to time GC modifies ptrAcqBuffer.</blockquote>
I'm not sure what's going on there. I'm not sure what
pin_ptr does when you try to give it something that isn't on the managed heap in the first place, so weird behavior is probably to be expected. Since you don't need the pin anyway, I wouldn't worry about it.