Csharp/CSharp Tutorial/unsafe/unsafe

Материал из .Net Framework эксперт
Версия от 15:20, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Accessing Structure Members with a Pointer

<source lang="csharp">using System;

public struct Point2D {

   public int X;
   public int Y;

}

public class MyClass {

   public unsafe static void Main()
   {
       Point2D MyPoint;
       Point2D * PointerToMyPoint;
  
       MyPoint = new Point2D();
       PointerToMyPoint = &MyPoint;
       PointerToMyPoint->X = 100;
       PointerToMyPoint->Y = 200;
       Console.WriteLine("({0}, {1})", PointerToMyPoint->X, PointerToMyPoint->Y);
   }

}</source>

Compile unsafe code

<source lang="csharp">// compile with: csc /unsafe ReadFileUnsafe.cs</source>

Mark method as unsafe to pointers

<source lang="csharp">using System;

class UnsafeCode {

 unsafe public static void Main() { 
   int count = 99; 
   int* p; // create an int pointer 

   p = &count; // put address of count into p 

   Console.WriteLine("Initial value of count is " + *p); 

   *p = 10; // assign 10 to count via p 
    
   Console.WriteLine("New value of count is " + *p); 
 } 

}</source>

Initial value of count is 99
New value of count is 10

unsafe block

<source lang="csharp">public struct MyValue {

   private int id;
   private decimal price;
   public MyValue(int id, decimal price) 
   {
       this.id = id;
       this.price = price;
   }
   override public string ToString() 
   {
       return String.Format("{0}: {1}", id, price);
   }
  
   unsafe public static void Swap(MyValue* pi, MyValue* pj)
   {
       MyValue tmp = *pi;
       *pi = *pj;
       *pj = tmp;
   }

}

class UnsafeStructApp {

   static void Main(string[] args)
   {
       MyValue i = new MyValue(123, 45.67m);
       MyValue j = new MyValue(890, 98.76m);
       Console.WriteLine("Before Swap:\ti = {0}, j = {1}", i, j);
  
       unsafe { MyValue.Swap(&i, &j); }
       Console.WriteLine("After Swap:\ti = {0}, j = {1}", i, j);
   }

}</source>

Unsafe Code

  1. C# allows you to write "unsafe" code.
  2. Unsafe code does not execute under the full management of the Common Language Runtime (CLR).
  3. Unsafe code often involves the use of pointers.
  4. Pointers are a bit like references in C#.
  5. The main difference is that a pointer can point anywhere in memory
  6. A reference always points to an object of its type.
  7. To compile unmanaged code, you must use the /unsafe compiler option.

33.1.unsafe 33.1.1. Unsafe Code 33.1.2. <A href="/Tutorial/CSharp/0620__unsafe/Compileunsafecode.htm">Compile unsafe code</a> 33.1.3. <A href="/Tutorial/CSharp/0620__unsafe/Usingunsafeandfixed.htm">Using unsafe and fixed</a> 33.1.4. <A href="/Tutorial/CSharp/0620__unsafe/Markmethodasunsafetopointers.htm">Mark method as unsafe to pointers</a> 33.1.5. <A href="/Tutorial/CSharp/0620__unsafe/AccessingStructureMemberswithaPointer.htm">Accessing Structure Members with a Pointer</a> 33.1.6. <A href="/Tutorial/CSharp/0620__unsafe/UnsafeMethods.htm">Unsafe Methods</a> 33.1.7. <A href="/Tutorial/CSharp/0620__unsafe/Usingtheunsafekeyword.htm">Using the unsafe keyword.</a> 33.1.8. <A href="/Tutorial/CSharp/0620__unsafe/unsafeblock.htm">unsafe block</a>

Unsafe Methods

<source lang="csharp">using System;

public class MyClass {

   public unsafe static void Main()
   {
       int MyInteger = 123;
       int * MyIntegerPointer = &MyInteger;
  
       Console.WriteLine(*MyIntegerPointer);
   }

}</source>

Using the unsafe keyword.

<source lang="csharp">using System; class MainClass {

   public static unsafe String UnsafeCodeExample(String s) {
       int len = s.Length;
       char[] str = new char[len + 1];
       string stemp = "";
       int nPos = 0;
       fixed (char* sptr = str) {
           // Copy the string in backward
           for (int i = len - 1; i >= 0; --i) {
               sptr[nPos++] = s[i];
               sptr[nPos] = (char)0;
           }
           // Now, copy it back
           for (int i = 0; i < len; ++i)
               stemp += sptr[i];
       }
       return stemp;
   }
   public static void Main() {
       String s = UnsafeCodeExample("This is a test");
       Console.WriteLine("Reversed: {0}", s);
   }

}</source>

Using unsafe and fixed

  1. Any code that uses pointers must be marked as unsafe by using the unsafe keyword.
  2. You can mark an individual statement or an entire method unsafe.
  1. The fixed modifier is often used when working with pointers.
  2. The fixed modifier prevents a managed variable from being moved by the garbage collector.

33.1.unsafe 33.1.1. <A href="/Tutorial/CSharp/0620__unsafe/UnsafeCode.htm">Unsafe Code</a> 33.1.2. <A href="/Tutorial/CSharp/0620__unsafe/Compileunsafecode.htm">Compile unsafe code</a> 33.1.3. Using unsafe and fixed 33.1.4. <A href="/Tutorial/CSharp/0620__unsafe/Markmethodasunsafetopointers.htm">Mark method as unsafe to pointers</a> 33.1.5. <A href="/Tutorial/CSharp/0620__unsafe/AccessingStructureMemberswithaPointer.htm">Accessing Structure Members with a Pointer</a> 33.1.6. <A href="/Tutorial/CSharp/0620__unsafe/UnsafeMethods.htm">Unsafe Methods</a> 33.1.7. <A href="/Tutorial/CSharp/0620__unsafe/Usingtheunsafekeyword.htm">Using the unsafe keyword.</a> 33.1.8. <A href="/Tutorial/CSharp/0620__unsafe/unsafeblock.htm">unsafe block</a>