zoukankan      html  css  js  c++  java
  • 编写不安全代码

    编写不安全代码

    MSDN:"尽管实际上对 C 或 C++ 中的每种指针类型构造,C# 都设置了与之对应的引用类型,但仍然会有一些场合需要访问指针类型。例如,当需要与基础操作系统进行交互、访问内存映射设备,或实现一些以时间为关键的算法时,若没有访问指针的手段,就不可能或者至少很难完成。为了满足这样的需求,C# 提供了编写不安全代码的能力。

    在不安全代码中,可以声明和操作指针,可以在指针和整型之间执行转换,还可以获取变量的地址,等等。在某种意义上,编写不安全代码很像在 C# 程序中编写 C 代码。"

    不安全代码必须用修饰符 unsafe 明确地标记。

    这里所谓的编写"不安全代码",就是要跳出.net CLR的限制,自己进行地址分配和垃圾回收.在C++里面,我们定义一个简单的指针,至少要做三件事,1.给他分配内存,2.保证类型转换正确3将内存空间释放,而在.net环境里,CLR将程序员从这些事情里解放出来,用户不再需要直接手工地进行内存操作。但是有时候,比如调用windows底层函数, 或是效率上的原因使我们需要自己去操作地址空间,本文主要是说明在c#里面指针的用法.

    指针的使用、操作内存

    1.& 和 *

        c++里面,我们很熟悉这两个东西.在c#里面他们也一样可以用,只不过含有他们的代码如果不在unsafe 标记下,编译器将会将它拒之门外.当然如果条件编译参数没有/unsafe 也是无法编译通过的(如果用vs.net集成编译环境,则在项目属性页-代码生成节将"允许不安全代码块"设置成true).

        &可以取得变量的地址,但是并不是所有的变量,托管类型,将无法取得其地址.c#里面,普通的值类型都是可以取得地址的,比如struct,int,long等,而class是无法取得其地址的,另外string是比较特殊的类型,虽然是值类型,但它也是受管的.这里插一下另一个运算符,sizeof,它也是仅可用于unsafe模式下.

    看下面这段代码,里面简单的用到了*,&,sizeof,还有c#里很少见但c++里大家很熟的->:

    class Class1
        
    {
            
    struct Point
            
    {
                
    public int x;
                
    public int y;
            }

            
    public static unsafe void Main() 
            
    {
                Point pt 
    = new Point();
                Point
    * pt1 = &pt;
                
    int* px = &(pt1->x);
                
    int* py = &(pt1->y);
                Console.WriteLine(
    "Address of pt is :0x{0:X} ",(uint)&pt);
                Console.WriteLine(
    "size of the struct :{0} ",sizeof(Point));
                Console.WriteLine(
    "Address of pt.x is :0x{0:X} ",(uint)&(pt.x));
                Console.WriteLine(
    "Address of pt.y is :0x{0:X} ",(uint)&(pt.y));
                Console.WriteLine(
    "Address of px is :0x{0:X} ",(uint)&(*px));
                Console.WriteLine(
    "Address of py is :0x{0:X} ",(uint)&(*py));
                Console.ReadLine();
            }

        }

    我这里运行的输出结果是:

    Address of pt is :0x12F698
    size of the struct :8
    Address of pt.x is :0x12F698
    Address of pt.y is :0x12F69C
    Address of px is :0x12F698
    Address of py is :0x12F69C

    可以看出struct的首地址与第一个成员变量的地址相同,而这个struct的长度是8个字节(=4+4).

    2.fixed

    虽然在unsafe模式下可以使用指针,但是unsafe的代码仍然是受管代码.CLR会对它的对象进行管理以及垃圾回收,CLR在这个过程中就会对内存进行重定位,可能过一段时间后,根据指针指向的地址就找不到原来的对象了,岂不是说指针在c#里没有什么实际的作用?别急,还有fixed.

    fixed 语句设置指向托管变量的指针并在fixed里的语句块执行期间“锁定”该变量(或者是几个变量)。如果没有 fixed 语句,则指向托管变量的指针将作用很小,因为垃圾回收可能不可预知地重定位变量。(实际上,除非在 fixed 语句中,否则 C# 不允许设置指向托管变量的指针。)

    看一段与刚才类似的代码,不同的地方是这里的输出地址的语句都在fixed块里.为什么不直接像第一个例子那样直接输出呢?这是因为我们对 Point进行了一个小小的改动,它不再是struct了,它现在是class!它是托管类型了,它的成员都没有固定的地址.但是在fixed块里,它的地址是固定的.

    class Point
            
    {    
                
    public static int x;
                
    public int y;
            }

            
    public static unsafe void Main() 
            
    {
                Point pt 
    = new Point();
                
    int[] arr = new int[10];
                
    //如果不用fixed语句,无论是静态成员还是实例成员,都将无法取得其地址。
                
    //int* ps = &CPoint.StaticField;
                
    //PrintAddress(ps);
                fixed (int* p = &Point.x)
                    Console.WriteLine(
    "Address is 0x{0:X}",(int)p);
                
    fixed (int* p = &pt.y) 
                    Console.WriteLine(
    "Address is 0x{0:X}",(int)p);
                
    fixed (int* p1 = &arr[0],p2 = arr)
                
    {
                    Console.WriteLine(
    "Address is 0x{0:X}",(int)p1);
                    Console.WriteLine(
    "Address is 0x{0:X}",(int)p2);
                }

                Console.ReadLine();
            }

    我这里运行的输出结果是:

    Address is 0x3D5404
    Address is 0x4BF1968
    Address is 0x4BF1978
    Address is 0x4BF1978

    3.分配内存

    在堆栈上分配内存

    c#提供stackalloc ,在堆栈上而不是在堆上分配一个内存块,语句为 type * ptr = stackalloc type [ expr ];它的大小足以包含 type 类型的 expr 元素;该块的地址存储在 ptr 指针中。此内存不受垃圾回收的制约,因此不必使用fixed将其固定。此内存块的生存期仅限于定义该内存块的方法的生存期。如果内存空间不足,将会抛出System.StackOverflowException异常.

    以下是一段示例程序(form msdn),

    public static unsafe void Main() 
    {
        int* fib = stackalloc int[100];
        int* p = fib;
        *p++ = *p++ = 1;    //fib[0]=fib[1]=1
        for (int i=2; i<100; ++i, ++p)
            *p = p[-1] + p[-2];//fib[i]=fib[i-1]+fib[i-2];
        for (int i=0; i<10; ++i)
            Console.WriteLine (fib[i]);
        Console.ReadLine();
    }
    
    在堆上分配内存

    既然有stackalloc,有没有heapalloc呢?答案是没有,c#没有提供这样的语法.想在堆上动态分配内存,只能靠自己想办法了.通过Kernel32.dll里的HeapAlloc()和HeapFree()可以达到这个目的.看下面的代码:

    using System;
    using System.Runtime.InteropServices;
    public unsafe class Memory
    {
        const int HEAP_ZERO_MEMORY = 0x00000008;//内存起始地址
        //获得进程堆的句柄
        [DllImport("kernel32")]
        static extern int GetProcessHeap();
        //内存分配
        [DllImport("kernel32")]
        static extern void* HeapAlloc(int hHeap, int flags, int size);
        //内存释放
        [DllImport("kernel32")]
        static extern bool HeapFree(int hHeap, int flags, void* block);
        static int ph = GetProcessHeap();//获得进程堆的句柄
        private Memory() {}
        public static void* Alloc(int size) //内存分配
        {
            void* result = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
            if (result == null) throw new OutOfMemoryException();
            return result;
        }
        public static void Free(void* block) //内存释放
        {
            if (!HeapFree(ph, 0, block)) throw new InvalidOperationException();
        }
    }
    class Test
    {
        unsafe static void Main() 
        {
            byte* buffer = (byte*)Memory.Alloc(256);
            for (int i = 0; i < 256; i++) 
                buffer[i] = (byte)i;
            for (int i = 0; i < 256; i++) 
                Console.WriteLine(buffer[i]);
            Memory.Free(buffer);
            Console.ReadLine();
        }
    }

  • 相关阅读:
    nexus3.x Liunx私库安装教程 (亲测有用)
    nexus 3.x下载 3.18.1(maven 私服)
    halo项目源码本地部署解决方案
    gradle的安装配置
    raw.githubusercontent.com 访问不了
    springboot使用quartz解决调用不到spring注入service的问题
    Linux在不能使用yum的环境下安装pgsql(公司内网)
    idea 里面的maven依赖下载不了,以及mabtis依赖包错误
    关于oracle 数据库效率的优化
    关于oracle 不常用的job 运行时间设置
  • 原文地址:https://www.cnblogs.com/binlyzhuo/p/1214861.html
Copyright © 2011-2022 走看看