C #-Unsafe code (unsafe)

Source: Internet
Author: User

C # unsafe code


Theory:

C # allows pointer variables to be used in a function when a block of code uses the unsafe modifier tag.

Unsafe or unmanaged code refers to a block of code that uses a pointer variable.


Pointer variable

A pointer is a variable that has the address of another variable, that is, the direct address of the memory location. Just like any other variable or constant, you must declare the pointer before you use the pointer to store other variable addresses.


The general form of a pointer variable declaration is: type *var-name;

The following is a valid pointer declaration:

int *ip;    /* point to an integer */double *DP;    /* point to a double-precision number */float *FP; /* point to a floating-point number */char *ch/* point to a character */

Example 1:


The following example illustrates the use of a pointer when the unsafe modifier is used in C #:

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 

Example 2:

You can also not declare the entire method as unsafe code, only part of the method is declared as unsafe code. This is illustrated in the following example.

Retrieving data values using pointers

You can use the ToString () method to retrieve data stored in the position referenced by the pointer variable. The following example demonstrates this:

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 result://data is: 20//data  is: 20//address is: 77128984

Example 3:

Passing pointers as arguments to methods

You can pass a pointer variable to a method as a parameter to a method. This is illustrated in the following 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

Example 4:

Using pointers to access array elements

In C #, the array name and a pointer to the same data type as the 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 the array data, you can use the fixed keyword to pin the pointer as we usually do in C or C + +.

The following example demonstrates this:

using system;namespace unsafecodeapplication{   class testpointer    {      public unsafe static void main ()        {         int[]  list =  {10, 100, 200};         fixed (int *ptr  = list)          /*  display pointer in array address  */          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 result://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

Example 5:

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, you would enter a 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 Propertiesby double-clicking the Properties node in Resource Manager (Solution Explorer).

    • Click the Build tab.

    • Select the option "Allowunsafe code".


Reference:

Http://outofmemory.cn/csharp/tutorial/csharp-unsafe-codes.html

This article comes from the "Ricky's blog" blog, please be sure to keep this source http://57388.blog.51cto.com/47388/1657405

C #-Unsafe code (unsafe)

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.