C # pointer unsafe/fixed--"one"

Source: Internet
Author: User

Pointer c#unsafefixed

Directory (?) [-]

    1. Overview
      1. Unsafe
      2. Fixed
1.1 Overview

The unsafe keyword represents an unsafe context, which is required for any operation involving pointers. You can use the unsafe modifier in the declaration of a property, method, class, and the entire body scope of a type or member is treated as an unsafe context.

The fixed statement is used to prevent the garbage collector from locating movable variables, and fixed can be used to create a constant-sized buffer that can only be in an unsafe context.

However, you can only manipulate structs when using pointers in C #, you cannot manipulate class, and you cannot use pointers of undefined types in generic type code.

When you compile unsafe code in C #, you must specify the/unsafe compiler option, otherwise you cannot verify unsafe code through the common language runtime, select the project-Properties-generate tag, and tick the "Allow unsafe code" option.



1.2 unsafe

You can add the unsafe keyword to a method or property:

C # Code
1
unsafe void Fun (byte* PS, byte* PD, int count)


You can also add the unsafe keyword to a class or struct :

C # Code
1
Unsafe class Demo

You can also use unsafe blocks so that unsafe code within that block can be used. For example :

C # Code
1
2
3
4
Unsafe Context:can use pointers here.
}

Complete examples:

C # Code
1
2
3
4
5
6
7
8
9
10
11
12
static void Squareptrparam (int *p)
{
*p *= *p;
}

Unsafe static void Main ()
{
int i = 5;
Squareptrparam (&i);
Console.WriteLine (i);
}

1.3 fixed

The fixed statement can be used to set a pointer to a managed variable and " pin " The variable during statement execution. If there is no fixed statement, the address of the pointer to the moveable managed variable is variable, because garbage collection may relocate the variable unpredictably.

The C # compiler only allows pointers to managed variables to be assigned in the fixed statement, but cannot modify the pointers initialized in the fixed statement.

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

C # Code
1
2
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 is of the same type:

C # Code
1
byte* PS = srcarray, PD = Dstarray) {...}

To initialize different types of pointers, you only need to nest the fixed statement:

C # Code
1
2
3
4
5
6
7
  int* p1 = &p.x)  

     fixed  (double* p2 = &array[ 5])  
    { 
        // do something with p1 and p2. 
    } 
}  


Complete Example:

C # Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
22
23
24
25
26
Class Point
{
Publicint x, y;
}

Class Fixedtest
{
UnsafeStaticvoid Squareptrparam (int *p)
{
*p *= *p;
}

UnsafeStaticvoid Main ()
{
Point pt =New Point ();
Pt.x = 5;
Pt.y = 6;

fixed (int *p = &pt.x)
{
Squareptrparam (P);
}

Console.WriteLine ("{0} {1}", Pt.x, Pt.y);
}
}

In unsafe mode, memory can be allocated on the stack, and the stack is not subject to garbage collection, so it does not need to be locked down, such as stack memory (stack memory is fast and efficient but limited in resources):

C # Code

1
2
3
4
5
6
7
8
&NBSP, void  fun ()
{
    int *p = stackalloc int[10];
    for  (int i  = 0; i < 10; i++)
    {
        p[i] = 2 * i + 2;
    }
}

C # pointer unsafe/fixed--"one"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.