SoFunction
Updated on 2025-03-06

C# method to achieve fast copying through pointers

This article describes the method of C# to achieve fast copying through pointers. Share it for your reference. The specific implementation method is as follows:

// 
// Used during compilation: /unsafeusing System;
class Test
{
  // The unsafe keyword is allowed in the following  // Use pointers in the 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 = ;
    int dstLen = ;
    if (srcLen - srcIndex < count || dstLen - dstIndex < count)
    {
      throw new ArgumentException();
    }
    // The following fixed statements are fixed    // The location of the src object and the dst object in memory to make these two objects    // It will not be moved by garbage collection.    fixed (byte* pSrc = src, pDst = dst)
    {
      byte* ps = pSrc;
      byte* pd = pDst;
      // Count in 4 byte blocks in a loop, copy at one time      // An integer (4 bytes):      for (int n = 0; n < count / 4; n++)
      {
        *((int*)pd) = *((int*)ps);
        pd += 4;
        ps += 4;
      }
      // Move all bytes that have not moved in a 4 byte block,      // Thus, the copy is completed:      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);
    ("The first 10 elements are:");
    for (int i = 0; i < 10; ++i)
      (b[i] + " ");
    ("\n");
  }
}

I hope this article will be helpful to everyone's C# programming.