Iris Classon
Iris Classon - In Love with Code

Stupid Question 122: What is meant by pinning objects in C#?

[To celebrate my first year of programming I will ask a ‘stupid’ questions daily on my blog for a year, to make sure I learn at least 365 new things during my second year as a developer]

Pinning down an address so we know where to go

Sounds fun? This has nothing to do with the popular site PinInterest- but we are pinning things (objects).

The problem with pointers are that as I explained in the pointer series (Stupid Question 118: The pointer series: What is a pointer?) a pointer points to an address in memory, a memory address. So we expect to find something, a particular thing, at that address. And the Garbage Collector likes to move stuff around (pointers in C# : Stupid Question 119: Do we have pointers in C#?) . Realocate objects. And it does so freely to make room, by gathering the items ,- more compact. Those good intentions cause problems for our pointer usage, and a way to solve this is by pinning the objects. By using the fixed keyword you tell the GarbageCollector not to move the object (only allowed in unsafe code:Stupid Question 121: What is meant by ‘unsafe code’ in .Net?). The object will keep its address so when we get the address for that party – we know it’s the right one.

Comments

Leave a comment below, or by email.
Lars Wilhelmsen
1/9/2013 1:17:34 PM
Hi,

 99.99% of the time you want to pin an object, you are doing P/Invoke or other bridging/marshalling out in the unmanaged memory space.

(Tip: do a "Stupid question" on P/Invoke - and check out www.pinvoke.net)

 --larsw 


Last modified on 2013-01-08

comments powered by Disqus