I have studied C ++ and C in college, and I am not very busy with my recent work. I think of the usage of pointers in C, the following learning notes are taken from the msdn: Fixed statement.
FixedStatement to prohibit the garbage collector from relocating movable variables.FixedStatements can only appear in insecure context.FixedIt can also be used to create a fixed-size buffer.
Remarks
FixedThe statement sets a pointer to the managed variable and "PIN" the variable during statement execution. If noFixedStatement, the pointer pointing to the movable hosted variable has little function, because garbage collection may unpredict the relocation of the variable. C # The Compiler only allowsFixedStatement.
// 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 isn‘t relocated.fixed ( int* p = &pt.x ){ *p = 1; }
You can use an array or string address to initialize the pointer:
fixed (int* p = arr) ... // equivalent to p = &arr[0]fixed (char* p = str) ... // equivalent to p = &str[0]
Multiple pointers can be initialized as long as the pointer types are the same:
fixed (byte* ps = srcarray, pd = dstarray) {...}
To initialize different types of pointers, you only need to nest them.FixedStatement:
fixed (int* p1 = &p.x){ fixed (double* p2 = &array[5]) { // Do something with p1 and p2. }}
After the code in the statement is executed, any fixed variable is removed from the fixed variable and is subject to garbage collection. Therefore, do not pointFixedVariables other than the statement.
| Note: |
The pointer initialized in the fixed statement cannot be modified. |
In unsafe mode, memory can be allocated on the stack. The stack is not restricted by garbage collection, so it does not need to be locked. For more information, see stackalloc.
Example
// statements_fixed.cs// compile with: /unsafeusing System;class Point{ public int x, y; }class FixedTest { // 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); }}Output
25 6
C # fixed statement for pointer learning notes