简体   繁体   English

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

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

Does the line fixed (int* pArray = &array[0]) from the example below pin the whole array, or just array[0] ? 从下面的例子中fixed (int* pArray = &array[0])的行是否fixed (int* pArray = &array[0])整个数组,或者只是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): 证明可以在C#语言规范中找到 (第18.6节固定语句 ,强调我的):

A fixed-pointer-initializer can be one of the following: fixed-pointer-initializer可以是以下之一:

... ...

  • 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. 如果类型T *可隐式转换为fixed语句中给出的指针类型,则表达具有非托管类型T的元素的数组类型。 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 ". 不幸的是,他们没有详细说明“ 类似结果 ”的含义,但值得注意的是,他们没有说“ 相同的结果 ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM