meci
meci

Reputation: 209

What is the correct way to access and manipulate pinned memory using GCHandle.Alloc()?

I'm trying to better understand what it takes to pin memory for longer periods of time. It's clear that GCHandle.Alloc(..., GCHandleType.Pinned) is what I need to use (over fixed(){}).

However, I was hoping I could get a bit of clarification on its use.

If I allocate an array and then use GCHandle to pin it:

byte[] data = new byte[10];
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);

and if I manipulate the data array like so:

for(int i = 0; i < data.length; i++) {
    data[i] = i;
}

am I still operating on the pinned area of memory? Or can I only access this memory via handle.AddrOfPinnedObject() function?

I'm sure this is probably a pretty basic question, but any help would be greatly appreciated!

Upvotes: 2

Views: 702

Answers (1)

user2864740
user2864740

Reputation: 61925

The original object remains valid for use - since that is still named by the given variable, keep using it. A new object is not created and the existing object is not invalidated. So, yes, the code will be "operating on the pinned area of memory".

The behavior of GCHandle.Alloc(.., GCHandleType.Pinned) is:

  • The object cannot be GC'ed before Free is called, even if it is no longer strongly reachable. This can cause a [true] memory leak if the handle is 'forgotten'.

  • The object cannot be moved during a GC compaction cycle nor can the object be moved between GC generations. This can result in reduced GC performance/efficiency.

Upvotes: 2

Related Questions