C#透過指標實現快速拷貝的方法

高洛峰
發布: 2017-01-19 13:22:01
原創
1497 人瀏覽過

本文實例講述了C#透過指標實現快速拷貝的方法。分享給大家供大家參考。具體實現方法如下:

// 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 对象在内存中的位置,以使这两个对象
    // 不会被垃圾回收移动。
    fixed (byte* pSrc = src, pDst = dst)
    {
      byte* ps = pSrc;
      byte* pd = pDst;
      // 以 4 个字节的块为单位循环计数,一次复制
      // 一个整数(4 个字节):
      for (int n = 0; n < count / 4; n++)
      {
        *((int*)pd) = *((int*)ps);
        pd += 4;
        ps += 4;
      }
      // 移动未以 4 个字节的块移动的所有字节,
      // 从而完成复制:
      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#程式設計有所幫助。

更多C#透過指標實現快速拷貝的方法相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!