C# study notes unsafe and pointers

In order to facilitate interaction with languages ​​such as C/C++, the concept of pointers is retained in C#. However, the use of pointers is strictly limited, so don't think that pointers can be used freely like C language. The pointer must be used in an "unsafe environment".

1.unsafe

unsafeThe keyword represents an insecure context. Any design pointer operation requires an unsafe context. unsafeUsed as a modifier for structures, classes, methods, properties, delegates, etc. E.g:

	static unsafe void FastCopy(byte[] src, byte[] dst, int count){
    
    
		// ... ...
	}

To compile unsafe programs (also known as "unmanaged code"), you must specify the /unsafe compilation option. Unmanaged code cannot be verified by the common language runtime.

2.fixed and pointer

fixedThe role of is to declare a pointer, using the following format:

	fixed(类型 * 指针名 = 表达式)语句

fixedThe keyword must be used in an unsafe environment. fixedThe statement sets a pointer to a managed variable and "locks" the variable during the execution of the statement, and indicates that the object pointed to by the pointer is not relocated by the garbage collector (because ordinary objects can be relocated by the garbage collector).
You can use a fixeddeclaration pointer to point to a variable or a domain in a class:

	Point pt = new Point();
	fixed(int * p = &pt.x){
    
    
		* p = 1;
	}

The pointer can be initialized with the address of an array or string:

	fixed(int * p = arr)...				// 相当于 p = &arr[0]
	fixed(char * p = str)...			// 相当于 p = &str[0]

As long as the pointers are of the same type, multiple pointers can be initialized; to initialize pointers of different types, nested fixedstatements are required .
Example UnsafeCopy.cs uses pointers to copy arrays:

// 编译时需要: /unsafe
using System;

class Program
{
    
    
	static unsafe void Copy(byte[] src, byte[] dst, int count) {
    
    
		int srcLen = src.Length;
		int dstLen = dst.Length;
		if (srcLen < count || dstLen < count)
			throw new ArgumentException();

		fixed (byte* pSrc = src, pDst = dst) {
    
    
			byte* ps = pSrc;
			byte* pd = pDst;
			for (int i = 0; i < count; i++) {
    
    
				*pd++ = *ps++;
			}
		}
	}

	static void Main(string[] args) {
    
    
		Console.WriteLine("Hello World!");
		byte[] a = new byte[100];
		byte[] b = new byte[100];

		for (int i = 0; i < 100; i++) {
    
    
			a[i] = (byte)i;
		}
		Copy(a, b, 100);
		Console.WriteLine("The first 10 elements are:");

		for (int i = 0; i < 10; i++) {
    
    
			Console.Write(b[i] + "{0}", i < 9 ? " " : "");
		}
	}
}

operation result:
Insert picture description here

3.sizeof operator

sizeofOperator, used to find the number of bytes occupied by a type. The format is as follows:

	sizeof(类型名)
	Console.WriteLine(sizeof(int));

sizeofIt can only be used for unmanaged types (referring to simple types, enumeration values, pointer types, and structure types that do not contain reference type members), and cannot be used for reference types. And sizeofcan only be used in unsafe environments.

4.stackalloc

stackallocKeyword, used to allocate memory on the stack, its format is as follows:

	类型 * p = stackalloc 类型[个数];

stackallocThe keyword can only be used in the unsafecontext, it can dynamically allocate memory, and the allocated memory is on the stack. It is not on the heap, so there is no worry about the memory being automatically reclaimed by the garbage collector.
For example, UnsafeStackAlloc.cs is used stackalloc.

using System;

class Test
{
    
    
	unsafe static string IntToString(int value) {
    
    
		char* buffer = stackalloc char[16];
		char* p = buffer + 16;
		int n = value >= 0 ? value : -value;
		do {
    
    
			*--p = (char)(n % 10 + '0');
			n /= 10;
		} while (n != 0);
	
		if (value < 0) *--p = '-';
		return new string(p, 0, (int)(buffer + 16 - p));
	}
	static void Main(){
    
    
		Console.WriteLine("IntToString");
		Console.WriteLine(IntToString(12345));
		Console.WriteLine(IntToString(-999));
	}
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114173985