How to bind the entire array in C # using the fixed keyword

The fixed (int* pArray = &array[0]) line fixed (int* pArray = &array[0]) from the example below binds the entire array, or just array[0] ?

 int array = new int[10]; unsafe { fixed (int* pArray = &array[0]) { } // or just 'array' } 
+8
c # unsafe fixed
source share
1 answer

The following statement:

 fixed (int* pArray = array) 

will fix the array full . Proof can be found in the C # Language Specification (section 18.6 Fixed Operator, my emphasis):

A fixed pointer initializer can be one of the following:

...

  • An expression of an array type with elements of an unmanaged type T, if the type T * is implicitly converted to the pointer type specified in the fixed statement. In this case, the initializer calculates the address of the first element in the array, and it is guaranteed that the entire array will remain at a fixed address for a fixed statement. ...

The following statement:

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

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

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

... and the third statement corrects and gets the address of the array element .


Side note: I would suggest that any normal implementation that fixes the first element just captures the entire array, but the specification does not guarantee it.

Digging a little deeper into the sample code in the spec, the following is revealed:

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

The fourth fixed operator in the above example gives a similar result to the third.

Unfortunately, they do not indicate what exactly they mean by “similar result”, but it is worth noting that they did not say “the same result”.

+6
source share

All Articles