如何使用关键字 fixed 在 C# 中固定整个数组

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

下面示例中的行 fixed (int* pArray = &array[0]) 是固定整个数组,还是只是 array[0]

int array = new int[10];
unsafe {
    fixed (int* pArray = &array[0]) { } // or just 'array'
}

以下声明:

fixed (int* pArray = array)

将修复 完整的 数组。证明可以在C# language specification(第18.6节固定语句,强调我的)中找到:

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

以下声明:

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

修复了第一个数组元素的地址。同样,引用规范(来自该章中的示例):

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

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


旁注:我假设任何修复 first 元素的合理实现都只是修复了整个数组,但规范似乎并不能保证这一点。

深入研究规范中的示例代码会发现以下内容:

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

不幸的是,他们没有具体说明“类似结果”的确切含义,但值得注意的是他们没有说“相同结果".