zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# 指针学习笔记之fixed 语句

c#笔记学习 语句 指针 fixed
2023-09-14 09:02:13 时间
fixed 语句设置指向托管变量的指针并在 statement 执行期间“钉住”该变量。如果没有 fixed 语句,则指向可移动托管变量的指针的作用很小,因为垃圾回收可能不可预知地重定位变量。C# 编译器只允许在 fixed 语句中分配指向托管变量的指针。


// assume class Point { public int x, y; }

// pt is a managed variable, subject to garbage collection.

Point pt = new Point();

// Using fixed allows the address of pt members to be

// taken, and "pins" pt so it isnt relocated.

fixed ( int* p = pt.x )

 *p = 1; 


 fixed (int* p = arr) ... // equivalent to p = arr[0]

fixed (char* p = str) ... // equivalent to p = str[0]


执行完语句中的代码后,任何固定变量都被解除固定并受垃圾回收的制约。因此,不要指向 fixed 语句之外的那些变量。


在不安全模式中,可以在堆栈上分配内存。堆栈不受垃圾回收的制约,因此不需要被锁定。有关更多信息,请参见 stackalloc


// Unsafe method: takes a pointer to an int. unsafe static void SquarePtrParam (int* p) *p *= *p; unsafe static void Main() Point pt = new Point(); pt.x = 5; pt.y = 6; // Pin pt in place: fixed (int* p = pt.x) SquarePtrParam (p); // pt now unpinned Console.WriteLine ("{0} {1}", pt.x, pt.y);
指针的那些用法 什么是指针? 从根本上看,指针是一个值为内存地址的变量。正如char类型变量的值是字符,int类型变量的值是整数,指针变量的值是地址。 因为计算机或者嵌入式设备的硬件指令非常依赖地址,指针在某种程度上把程序员想要表达的指令以更接近机器的方式表达,因此,使用指针的程序更有效率。尤其是指针能够有效地处理数组,而数组表示法其实是在变相的使用指针,比如:数组名是数组首元素的地址。
C++:delete不完整类型的指针 以下代码编译时会有warning: class X; void foo(X* x) { delete x; 在GCC4.1.2下,编译出错信息是: warning: possible problem detected in invocation of delete oper.