How to pin the whole array in C# using the keyword fixed
Asked Answered
W

1

9

Does the line fixed (int* pArray = &array[0]) from the example below pin the whole array, or just array[0]?

int array = new int[10];
unsafe {
    fixed (int* pArray = &array[0]) { } // or just 'array'
}
Waikiki answered 3/9, 2015 at 20:12 Comment(5)
i think no. you have to do fixed (int* pArray = array)Staghound
@M.kazemAkhgary, no, that won't work: CS0208 Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')Sonyasoo
@ThomasLevesque dont put & before array. just write (int* pArray = array)Staghound
@M.kazemAkhgary, good point. This way it works.Sonyasoo
Some additional advice from Mr. Lippert: What’s the difference? fixed versus fixed and Taking responsibilityEquites
B
8

The following statement:

fixed (int* pArray = array)

will fix the complete array. Proof can be found in the C# language specification (Section 18.6 The fixed statement, emphasis mine):

A fixed-pointer-initializer can be one of the following:

...

  • An expression of an array-type with elements of an unmanaged type T, provided the type T* is implicitly convertible to the pointer type given in the fixed statement. In this case, the initializer computes the address of the first element in the array, and the entire array is guaranteed to remain at a fixed address for the duration of the fixed statement. ...

The following statement:

fixed (int* pArray = &array[0])

fixes the address of the first array element. Again, a quote from the specification (from an example found in that chapter):

...    
[third fixed statement:] fixed (int* p = &a[0]) F(p);
...

...and the third statement fixes and obtains the address of an array element.


Side note: I would assume that any sane implementation that fixes the first element simply fixes the whole array, but the specification does not seem to guarantee it.

Digging a bit deeper into the example code in the specification reveals the following:

...    
[third fixed statement:]  fixed (int* p = &a[0]) F(p);
[fourth fixed statement:] fixed (int* p = a) F(p);
...

The fourth fixed statement in the example above produces a similar result to the third.

Unfortunately, they do not specify what exactly they mean by "similar result", but it is worth noting that they did not say "same result".

Bove answered 3/9, 2015 at 20:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.