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'
}
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'
}
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".
© 2022 - 2024 — McMap. All rights reserved.
fixed (int* pArray = array)
– StaghoundCS0208 Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
– Sonyasoo&
beforearray
. just write(int* pArray = array)
– Staghound