Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

fixed

unsafe

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'
}
like image 487
Jenix Avatar asked Sep 03 '15 20:09

Jenix


1 Answers

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".

like image 153
Heinzi Avatar answered Oct 30 '22 08:10

Heinzi