分享

使用非托管代码进行字节数组的快速拷贝

 kittywei 2012-02-17

今天在阅读MSDN时发现了该方法示例,感觉在C#环境下也可以这样,真是一个不错的idea,不过没有具体验证过其效率,有兴趣的朋友可以自己验证一下。

 


 1class TestCopy
 2{
 3    // The unsafe keyword allows pointers to be used within the following method:
 4    static unsafe void Copy(byte[] src, int srcIndex, byte[] dst, int dstIndex, int count)
 5    {
 6        if (src == null || srcIndex < 0 ||
 7            dst == null || dstIndex < 0 || count < 0)
 8        {
 9            throw new System.ArgumentException();
10        }

11
12        int srcLen = src.Length;
13        int dstLen = dst.Length;
14        if (srcLen - srcIndex < count || dstLen - dstIndex < count)
15        {
16            throw new System.ArgumentException();
17        }

18
19        // The following fixed statement pins the location of the src and dst objects
20        // in memory so that they will not be moved by garbage collection.
21        fixed (byte* pSrc = src, pDst = dst)
22        {
23            byte* ps = pSrc;
24            byte* pd = pDst;
25
26            // Loop over the count in blocks of 4 bytes, copying an integer (4 bytes) at a time:
27            for (int i = 0 ; i < count / 4 ; i++)
28            {
29                *((int*)pd) = *((int*)ps);
30                pd += 4;
31                ps += 4;
32            }

33
34            // Complete the copy by moving any bytes that weren't moved in blocks of 4:
35            for (int i = 0; i < count % 4 ; i++)
36            {
37                *pd = *ps;
38                pd++;
39                ps++;
40            }

41        }

42    }

43
44    static void Main()
45    {
46        byte[] a = new byte[100];
47        byte[] b = new byte[100];
48
49        for (int i = 0; i < 100++i)
50        {
51            a[i] = (byte)i;
52        }

53
54        Copy(a, 0, b, 0100);
55        System.Console.WriteLine("The first 10 elements are:");
56
57        for (int i = 0; i < 10++i) 
58        {
59            System.Console.Write(b[i] + " ");
60        }

61        System.Console.WriteLine("\n");
62    }

63}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多