Managed code: the code that is executed by the Common Language Runtime Library environment (rather than directly by the operating system. Managed code applications can obtain the public Language Runtime library service, such as automatic
Garbage collection, runtime database type check, and security support. These services help provide unified managed code application behavior independent of platform and language. Unmanaged Code: the Code that is directly executed by the operating system outside the public Language Runtime Library environment. Unmanaged code must provide its own garbage collection, type check, and security support
It is different from the managed code, which is obtained from the public Language Runtime Library.
The Unsafe code is between the two. It is also executed in the CLR environment, but we can directly operate on the memory. As long as our code contains one of the following three pointer operators, we need to use Unsafe.
Keywords:
*
&
->
For example:
unsafe static void ChangeValue(int* pInt) { *pInt = 23; }
The above code is executed under the CLR. To reduce memory fragments, the automatic garbage collection mechanism of C # will allow the allocated memory to be adjusted at runtime, so if we call it multiple times
Causes the pointer to point to another variable. For example* PInt is
The address pointing to a variable is 1001, And the CLR stores the variable in the address 5001 after the memory is re-allocated. In the past, 1001 may
Other variables are allocated. To solve this problem, we need to use the Fixed keyword.
The fixed statement prohibits the garbage collector from relocating movable variables. Fixed statements can only appear in insecure context. Fixed can also be used to create a Fixed-size buffer. For example:
Using System; class CaryData {public int data;} class CProgram {unsafe static void ChangeValue (int * pInt) {* pInt = 23;} public unsafe static void Main () {CaryData cd = new CaryData (); Console. writeLine ("Before change: {0}", cd. data); fixed (int * p = & cd. data) {ChangeValue (p);} Console. writeLine ("changed: {0}", cd. data );}}
Check the security code that allows tags to be generated in project properties.