Nested Fixed Operator

According to C # reference for the fixed operator:

The fixed statement prevents the garbage collector from moving the movable variable.
...
After executing the code in the instruction, any fixed variables are not fixed and are subject to garbage collection. Therefore, do not point to these variables outside the fixed operator.

My question is: what I did not find on this page, what will happen if we have a fixed statement for the same variable?

 var data = new byte[100]; unsafe { fixed(byte* pData = data) { //pData points to the "pinned" variable fixed(byte* pData2 = data) { //pData points to the "pinned" variable //pData2 points to the "pinned" variable } //Does pData still point to the "pinned" variable? } } 

The code above is considered, of course, for illustration purposes only. Practical use can be recursive.

+3
garbage-collection c # unsafe
source share
1 answer

It works the way you expected it to work, certainly it is. A fixed property is associated with a pointer variable, and not with the object that it binds. Thus, inside the internal block of visibility, there are two variables that bind the array. Then one of them contains one variable that binds it. It is still fixed.

When you recurs and the array is declared outside the method, then there will be many other variables that bind it.

A decent mental image should work from the assumption that the fixed initializes the GCHandle for the object. You can create as many GCHandles for an object as you dare, GC doesn't mind. This does not actually happen at run time, it is fixed much more efficiently than GCHandle. This is a variable attribute, shown as [pinned] in a disassembler such as ildasm.exe. The GC detects an attribute as it walks along the glass, looking for references to objects.

+5
source share

All Articles