zoukankan      html  css  js  c++  java
  • C#中指针的简单使用

    原来C#不仅仅支持和C/C++中指针(或者说是引用)很像的委托delegate,还支持在unsafe代码块中使用指针,从而写非托管的代码(人为不让垃圾回收机制来管理相应的内存)。在unsafe中就可以使用指针,基本用法和C++差不多(果然是一家人,哈哈)。

    在用指针调用数组的时候需要使用fixed语句(只能在unsafe语句块中使用)来固定指针变量的初始值,否则可能被垃圾回收机制改变指针变量的值,fixed语句可以禁止垃圾回收机制重定位可移动的变量。

    fixed语句中可以设置指向托管变量的指针,并且执行该语句期间可以固定某变量。

    基本语法

       fixed (<需要固定的变量>)

         {   <fixed语句块,内部可以用指针对托管变脸操作>   }

    下面上一个操作数组的简单例子:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.IO;
     7 using System.Collections.Generic;
     8 
     9 namespace CsharpStudy
    10 {
    11 
    12    
    13 
    14 
    15 
    16     class Program
    17     {
    18 
    19 
    20         static void Main(string[] args)
    21         {
    22             /************Main function***************/
    23 
    24             unsafe 
    25             {
    26                 int[] list = new int[3]{10, 20, 30};
    27 
    28                 fixed (int* p = list)
    29                 {
    30                     for (int i = 0; i < 3; i++)
    31                     {
    32                         Console.WriteLine(*(p + i));
    33                     }
    34 
    35                 }
    36             }
    37             
    38 
    39             /****************************************/
    40             Console.WriteLine();
    41             Console.ReadKey();
    42         }
    43     }
    44 
    45 
    46 }

    例子的结果图是

     注意,在VS中运行unsafe的代码的时候需要在project的属性中找到bulid,勾选允许非安全的代码这一项。

  • 相关阅读:
    javascript深入理解js闭包
    hibernate 之 sql查询
    MongoDB 2.4企业版分析
    MongoDB 连接池
    GridFS实现原理
    MongoVUE破解
    mongodb 官方 手册
    mongodb的一些性能管理工具
    Python: names, values, assignment and mutability
    使用 mock 测试
  • 原文地址:https://www.cnblogs.com/jeavenwong/p/8537610.html
Copyright © 2011-2022 走看看