[C#] C# 通过指针实现的fastcopy →→→→→进入此内容的聊天室

来自 , 2021-03-18, 写在 C#, 查看 133 次.
URL http://www.code666.cn/view/71ee911d
  1. // fastcopy.cs
  2. // 编译时使用:/unsafe
  3. using System;
  4.  
  5. class Test
  6. {
  7.     // unsafe 关键字允许在下列
  8.     // 方法中使用指针:
  9.     static unsafe void Copy(byte[] src, int srcIndex,
  10.         byte[] dst, int dstIndex, int count)
  11.     {
  12.         if (src == null || srcIndex < 0 ||
  13.             dst == null || dstIndex < 0 || count < 0)
  14.         {
  15.             throw new ArgumentException();
  16.         }
  17.         int srcLen = src.Length;
  18.         int dstLen = dst.Length;
  19.         if (srcLen - srcIndex < count ||
  20.             dstLen - dstIndex < count)
  21.         {
  22.             throw new ArgumentException();
  23.         }
  24.  
  25.  
  26.         // 以下固定语句固定
  27.         // src 对象和 dst 对象在内存中的位置,以使这两个对象
  28.         // 不会被垃圾回收移动。
  29.         fixed (byte* pSrc = src, pDst = dst)
  30.         {
  31.             byte* ps = pSrc;
  32.             byte* pd = pDst;
  33.  
  34.             // 以 4 个字节的块为单位循环计数,一次复制
  35.             // 一个整数(4 个字节):
  36.             for (int n = 0; n < count / 4; n++)
  37.             {
  38.                 *((int*)pd) = *((int*)ps);
  39.                 pd += 4;
  40.                 ps += 4;
  41.             }
  42.  
  43.             // 移动未以 4 个字节的块移动的所有字节,
  44.             // 从而完成复制:
  45.             for (int n = 0; n < count % 4; n++)
  46.             {
  47.                 *pd = *ps;
  48.                 pd++;
  49.                 ps++;
  50.             }
  51.         }
  52.     }
  53.  
  54.  
  55.     static void Main(string[] args)
  56.     {
  57.         byte[] a = new byte[100];
  58.         byte[] b = new byte[100];
  59.         for (int i = 0; i < 100; ++i)
  60.             a[i] = (byte)i;
  61.         Copy(a, 0, b, 0, 100);
  62.         Console.WriteLine("The first 10 elements are:");
  63.         for (int i = 0; i < 10; ++i)
  64.             Console.Write(b[i] + " ");
  65.         Console.WriteLine("\n");
  66.     }
  67. }
  68. //csharp/4926

回复 "C# 通过指针实现的fastcopy"

这儿你可以回复上面这条便签

captcha