美文网首页c#学习
C#里面的指针

C#里面的指针

作者: 李药师_hablee | 来源:发表于2019-12-24 21:20 被阅读0次

    先贴代码

    实现的是一个复制的功能

    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 编译的情况下出现这样的问题,那么你需要设置一下当前项目的属性:

    调试->属性
    生成->勾选中箭头的选项

    相关文章

      网友评论

        本文标题:C#里面的指针

        本文链接:https://www.haomeiwen.com/subject/tyzfoctx.html