unsafeKeyword represents an unsafe context that is required by any operation involving pointers. For more information, see Unsafe Code and Pointers (C # Programming Guide).
You can use the unsafe modifier in the declaration of a type or member. Therefore, the entire body scope of a type or member is considered an unsafe context. For example, the following is a method declared with the unsafe modifier:
[CSharp]View plain copy unsafe static void FastCopy (byte[) src, byte[] DST, int count) {//unsafe Context:can Use Pointe RS here. }
The scope of the unsafe context extends from the argument list to the end of the method, so the pointer can also be used in the following argument list:
[CSharp]View plain copy unsafe static void FastCopy (byte* PS, byte* PD, int count) {...}
You can also use unsafe blocks to be able to use unsafe code within that block. For example:
[CSharp]View Plain Copy Unsafe {//unsafe context:can use pointers here. }
To compile unsafe code, you must specify the/unsafe compiler option. Unsafe code cannot be validated through the common language runtime. Example
[CSharp] View Plain copy// cs_unsafe_keyword.cs // compile with: /unsafe using System; class unsafetest { // Unsafe method: takes pointer to int: unsafe static void squareptrparam (int* p) { *p *= *p; } unsafe Static void main () { int i = 5; // unsafe method: uses address-of operator (&): squareptrparam ( &i); console.writeline (i); } }
Output
-
The fixed statement prevents the garbage collector from relocating the movable variable. A fixed statement can only be present in an unsafe context. Fixed
The fixed statement sets a pointer to a managed variable and "pegs" the variable during statement execution. If there are no fixed statements, pointers to removable managed variables have little effect because garbage collection can reposition variables unpredictably. The C # compiler allows only pointers to managed variables to be assigned in the fixed statement.
[CSharp] View Plain Copy// 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 &nb