• 当前位置:首页>>C#语言>>C#基础教程>>C# 程序员参考--不安全代码教程
  • C# 程序员参考--不安全代码教程
  • 该教程说明如何在 C# 中使用不安全代码(使用指针的代码)。

    教程

    在 C# 中很少需要使用指针,但仍有一些需要使用的情况。例如,在下列情况中使用允许采用指针的不安全上下文是正确的:

    • 处理磁盘上的现有结构
    • 涉及内部包含指针的结构的高级 COM 或平台调用方案
    • 性能关键代码

    不鼓励在其他情况下使用不安全上下文。具体地说,不应该使用不安全上下文尝试在 C# 中编写 C 代码。

    警告   使用不安全上下文编写的代码无法被验证为安全的,因此只有在代码完全受信任时才会执行该代码。换句话说,不可以在不受信任的环境中执行不安全代码。例如,不能从 Internet 上直接运行不安全代码。

    该教程包括下列示例:

    • 示例 1   使用指针复制一个字节数组。
    • 示例 2   显示如何调用 Windows ReadFile 函数。
    • 示例 3   显示如何打印可执行文件的 Win32 版本。

    示例 1

    以下示例使用指针将一个字节数组从 src 复制到 dst。用 /unsafe 选项编译此示例。

    // fastcopy.cs
    
    // compile with: /unsafe
    
    using System;
    
     
    
    class Test
    
    {
    
        // The unsafe keyword allows pointers to be used within
    
        // the following method:
    
        static unsafe void Copy(byte[] src, int srcIndex,
    
            byte[] dst, int dstIndex, int count)
    
        {
    
            if (src == null || srcIndex < 0 ||
    
                dst == null || dstIndex < 0 || count < 0)
    
            {
    
                throw new ArgumentException();
    
            }
    
            int srcLen = src.Length;
    
            int dstLen = dst.Length;
    
            if (srcLen - srcIndex < count ||
    
                dstLen - dstIndex < count)
    
            {
    
                throw new ArgumentException();
    
            }
    
     
    
     
    
                // The following fixed statement pins the location of
    
                // the src and dst objects in memory so that they will
    
                // not be moved by garbage collection.          
    
                fixed (byte* pSrc = src, pDst = dst)
    
                {
    
                      byte* ps = pSrc;
    
                      byte* pd = pDst;
    
    
    
                // Loop over the count in blocks of 4 bytes, copying an
    
                // integer (4 bytes) at a time:
    
                for (int n =0 ; n < count/4 ; n++)
    
                {
    
                    *((int*)pd) = *((int*)ps);
    
                    pd += 4;
    
                    ps += 4;
    
                }
    
     
    
                // Complete the copy by moving any bytes that weren't
    
                // moved in blocks of 4:
    
                for (int n =0; n < count%4; n++)
    
                {
    
                    *pd = *ps;
    
                    pd++;
    
                    ps++;
    
                }
    
                }
    
        }
    
     
    
     
    
        static void Main(string[] args) 
    
        {
    
            byte[] a = new byte[100];
    
            byte[] b = new byte[100];
    
            for(int i=0; i<100; ++i) 
    
               a[i] = (byte)i;
    
            Copy(a, 0, b, 0, 100);
    
            Console.WriteLine("The first 10 elements are:");
    
            for(int i=0; i<10; ++i) 
    
               Console.Write(b[i] + " ");
    
            Console.WriteLine("\n");
    
        }
    
    }

    输出示例

    The first 10 elements are:
    
    0 1 2 3 4 5 6 7 8 9

    代码讨论

    • 请注意使用了 unsafe 关键字,这允许在 Copy 方法内使用指针。
    • fixed 语句用于声明指向源和目标数组的指针。它锁定 src 和 dst 对象在内存中的位置以便使其不会被垃圾回收移动。当 fixed 块完成后,这些对象将被解除锁定。
    • 通过略过数组界限检查,不安全代码可提高性能。

    示例 2

    本示例显示如何从 Platform SDK 调用 Windows ReadFile 函数,这要求使用不安全上下文,因为读缓冲区需要将指针作为参数。

    [1] [2] [3] [4] 下一页