C × unsafe code
When a code block is marked with the unsafe modifier, C ා allows pointer variables to be used in functions. Unsafe or unmanaged code refers to blocks of code that use pointer variables.
Pointer variable
A pointer is a variable whose value is the address of another variable, that is, the direct address of the memory location. Just like other variables or constants, pointers must be declared before they can be used to store other variable addresses.
The general form of pointer variable declaration is:
type* var-name;
Here is an example of a pointer type declaration:
When multiple pointers are declared in the same declaration, the asterisk * is written only with the underlying type; it is not used as a prefix for each pointer name. For example:
int* p1, p2, p3; // Correct int *p1, *p2, *p3; // error
The following example illustrates the use of pointers when the unsafe modifier is used in C ා:
Example
using System; namespace UnsafeCodeApplication { class Program { static unsafe void Main(string[] args) { int var = 20; int* p = &var; Console.WriteLine("Data is: {0} ", var); Console.WriteLine("Address is: {0}", (int)p); Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following results:
Data is: 20 Address is: 99215364
You can also not declare the entire method as unsafe code, only a part of the method as unsafe code. The following example illustrates this.
Retrieving data values using pointers
You can use the ToString() method to retrieve the data stored in the location referenced by the pointer variable. The following example demonstrates this:
Example
using System; namespace UnsafeCodeApplication { class Program { public static void Main() { unsafe { int var = 20; int* p = &var; Console.WriteLine("Data is: {0} " , var); Console.WriteLine("Data is: {0} " , p->ToString()); Console.WriteLine("Address is: {0} " , (int)p); } Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following results:
Data is: 20 Data is: 20 Address is: 77128984
Passing a pointer as a parameter to a method
You can pass a pointer variable to a method as a parameter to the method. The following example illustrates this:
Example
using System; namespace UnsafeCodeApplication { class TestPointer { public unsafe void swap(int* p, int *q) { int temp = *p; *p = *q; *q = temp; } public unsafe static void Main() { TestPointer p = new TestPointer(); int var1 = 10; int var2 = 20; int* x = &var1; int* y = &var2; Console.WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2); p.swap(x, y); Console.WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2); Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following results:
Before Swap: var1: 10, var2: 20 After Swap: var1: 20, var2: 10
Using pointers to access array elements
In C, array name and a pointer to the same data type as array data are different variable types. For example, int *p and int[] p are different types. You can increase the pointer variable p, because it is not fixed in memory, but the array address is fixed in memory, so you cannot increase the array P.
Therefore, if you need to use pointer variables to access array data, you can use fixed keyword to fix the pointer as we usually do in C or C + +.
The following example demonstrates this:
Example
using System; namespace UnsafeCodeApplication { class TestPointer { public unsafe static void Main() { int[] list = {10, 100, 200}; fixed(int *ptr = list) /* Display array address in pointer */ for ( int i = 0; i < 3; i++) { Console.WriteLine("Address of list[{0}]={1}",i,(int)(ptr + i)); Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i)); } Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following results:
Address of list[0] = 31627168 Value of list[0] = 10 Address of list[1] = 31627172 Value of list[1] = 100 Address of list[2] = 31627176 Value of list[2] = 200
Compiling unsafe code
In order to compile unsafe code, you must switch to the command line compiler to specify the / unsafe command line.
For example, to compile a program named prog1.cs that contains unsafe code, enter the command on the command line:
csc /unsafe prog1.cs
If you are using the Visual Studio IDE, you need to enable unsafe code in the project properties.
The steps are as follows:
- Open project properties by double clicking the properties node in the Solution Explorer.
- Click the Build tab.
- Select the option Allow unsafe code.
fixed keyword
Since the storage of variables declared in C ා in memory is managed by the garbage collector, it is possible for a variable (such as a large array) to be moved to another location in memory during the run. If the memory address of a variable changes, then the pointer is meaningless.
The solution is to use the fixed keyword to fix the variable position.
static unsafe void Main(string[] args) { fixed(int *ptr = int[5]) {//...} } stackalloc
In unsafe environment of unsafe environment, we can allocate memory on the stack through stackalloc, because the memory allocated on the stack is not managed by memory manager, so its corresponding pointer does not need to be fixed.
static unsafe void Main(string[] args) { int *ptr = stackalloc int[1] ; }
The code after adding the keyword unsafe will be reported as an error by the VS compilation environment. The error message is "unsafe code will only appear when compiled with / unsafe".
resolvent:
- 1. You need to find the (item identifier) property item in the item menu above. Click to enter the project property setting interface.
- 2. Find the build tab in the project properties interface.
- 3. find "allow unsafe code" in the "generate" tab and check this item.
- 4. Compile the program at this time, and you can completely solve this problem.
Or use the compile command such as CSC / unsafe unsafe unsafe.cs under DOS (unsafe.cs is only a source code file for example).