1、遇到的问题
1 unsafe
2 {
3        fixed (byte* ptrdata = dataGrayScaleImage)
4              for (int i = 0; i < height; i++)
5              {
6                     ...          
7              }
8 }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

解析:

  1、fixed 语句禁止垃圾回收器重定位可移动的变量。fixed 语句只能出现在不安全的上下文中。Fixed 还可用于创建固定大小的缓冲区。
  2、fixed 语句设置指向托管变量的指针并在 statement 执行期间“钉住”该变量。如果没有 fixed 语句,则指向可移动托管变量的指针的作用很小,因为垃圾回收可能不可预知地重定位变量。C# 编译器只允许在 fixed 语句中分配指向托管变量的指针。
  3、执行完语句中的代码后,任何固定变量都被解除固定并受垃圾回收的制约。因此,不要指向 fixed 语句之外的那些变量。

详见:C# fixed详解
2、初始化多个相同类型的指针时:
1 fixed (byte* ptrdataRed = dataRed , ptrdataGreen = dataGreen, ptrdataBlue = dataBlue)
2 {
3       ...
4 }
  • 1.
  • 2.
  • 3.
  • 4.
3、初始化多个不同类型的指针时,使用嵌套:
1 fixed(byte *p=&t)
2 {    
3     fixed(int* m=&m)
4     {
5         ...
6     }
7 }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.



作者:꧁执笔小白꧂