欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#通過指針實現(xiàn)快速拷貝的方法

 更新時間:2015年06月10日 09:29:18   作者:pythoner  
這篇文章主要介紹了C#通過指針實現(xiàn)快速拷貝的方法,涉及C#指針的相關使用技巧,需要的朋友可以參考下

本文實例講述了C#通過指針實現(xiàn)快速拷貝的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:

// fastcopy.cs
// 編譯時使用:/unsafe
using System;
class Test
{
  // unsafe 關鍵字允許在下列
  // 方法中使用指針:
  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 = src.Length;
    int dstLen = dst.Length;
    if (srcLen - srcIndex < count || dstLen - dstIndex < count)
    {
      throw new ArgumentException();
    }
    // 以下固定語句固定
    // src 對象和 dst 對象在內(nèi)存中的位置,以使這兩個對象
    // 不會被垃圾回收移動。
    fixed (byte* pSrc = src, pDst = dst)
    {
      byte* ps = pSrc;
      byte* pd = pDst;
      // 以 4 個字節(jié)的塊為單位循環(huán)計數(shù),一次復制
      // 一個整數(shù)(4 個字節(jié)):
      for (int n = 0; n < count / 4; n++)
      {
        *((int*)pd) = *((int*)ps);
        pd += 4;
        ps += 4;
      }
      // 移動未以 4 個字節(jié)的塊移動的所有字節(jié),
      // 從而完成復制:
      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);
    Console.WriteLine("The first 10 elements are:");
    for (int i = 0; i < 10; ++i)
      Console.Write(b[i] + " ");
    Console.WriteLine("\n");
  }
}

希望本文所述對大家的C#程序設計有所幫助。

相關文章

最新評論