c#学习

C#里面的指针

2019-12-24  本文已影响0人  李药师_hablee

先贴代码

实现的是一个复制的功能

using System;

namespace ConsoleApp2
{
    class Program
    {
        static unsafe void Copy(byte[] src,byte[] dst, int count)
        {
            int srcLen = src.Length;
            int dstLen = dst.Length;
            if(srcLen<count||dstLen<count)
            {
                throw new ArgumentException();
            }
            fixed (byte* pSrc=src, pDst=dst)
            {
                byte* ps = pSrc;
                byte* pd = pDst;
                for(int n=0;n<count;n++)
                {
                    *pd++ = *ps++;
                }
            }
        }
        static void Main()
        {
            byte[] a = new byte[100];
            byte[] b = new byte[100];
            for(int i=0;i<100;i++)
            {
                a[i] = (byte)i;
            }
            Copy(a, b, 100);
            Console.WriteLine("The first 10 elements are:");
            for (int i = 0; i < 10; i++)
                Console.Write(b[i] + "{0}", i < 9 ? " " : "");
            //Console.WriteLine();
        }
    }
}

注意出现的错误警告

如果你在编译过程中出现了错误CS0227不安全代码只会在使用 /unsafe 编译的情况下出现这样的问题,那么你需要设置一下当前项目的属性:

调试->属性
生成->勾选中箭头的选项
上一篇 下一篇

猜你喜欢

热点阅读