Copies a block of memory from one location to another. - CSharp Unsafe

CSharp examples for Unsafe:Memory

Description

Copies a block of memory from one location to another.

Demo Code


using System.Diagnostics;
using System.Collections.Generic;
using System.Collections;
using System.Runtime.InteropServices;
using System;/* ww  w.j  a  va2s  .c  om*/

public class Main{
        /// <summary>
      /// Copies a block of memory from one location to another.
      /// </summary>
      /// <param name="dest">Pointer to the starting address of the copy destination.</param>
      /// <param name="src">Pointer to the starting address of the block of memory to be copied.</param>
      /// <param name="len">Size of the block of memory to copy, in bytes.</param>
      protected static unsafe void CopyMemory(byte* dest, byte* src, int len)
      {
         if (len >= 0x10)
         {
            do
            {
               *((int*)dest) = *((int*)src);
               *((int*)(dest + 4)) = *((int*)(src + 4));
               *((int*)(dest + 8)) = *((int*)(src + 8));
               *((int*)(dest + 12)) = *((int*)(src + 12));
               dest += 0x10;
               src += 0x10;
            }
            while ((len -= 0x10) >= 0x10);
         }
         if (len > 0)
         {
            if ((len & 8) != 0)
            {
               *((int*)dest) = *((int*)src);
               *((int*)(dest + 4)) = *((int*)(src + 4));
               dest += 8;
               src += 8;
            }
            if ((len & 4) != 0)
            {
               *((int*)dest) = *((int*)src);
               dest += 4;
               src += 4;
            }
            if ((len & 2) != 0)
            {
               *((short*)dest) = *((short*)src);
               dest += 2;
               src += 2;
            }
            if ((len & 1) != 0)
            {
               *dest = *src;
            }
         }
      }
}

Related Tutorials