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

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

 

ContractedBlock.gif ExpandedBlockStart.gif Code
 1class TestCopy
 2ExpandedBlockStart.gifContractedBlock.gif{
 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)
 5ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 6        if (src == null || srcIndex < 0 ||
 7            dst == null || dstIndex < 0 || count < 0)
 8ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 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)
15ExpandedSubBlockStart.gifContractedSubBlock.gif        {
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)
22ExpandedSubBlockStart.gifContractedSubBlock.gif        {
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++)
28ExpandedSubBlockStart.gifContractedSubBlock.gif            {
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++)
36ExpandedSubBlockStart.gifContractedSubBlock.gif            {
37                *pd = *ps;
38                pd++;
39                ps++;
40            }

41        }

42    }

43
44    static void Main()
45ExpandedSubBlockStart.gifContractedSubBlock.gif    {
46        byte[] a = new byte[100];
47        byte[] b = new byte[100];
48
49        for (int i = 0; i < 100++i)
50ExpandedSubBlockStart.gifContractedSubBlock.gif        {
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) 
58ExpandedSubBlockStart.gifContractedSubBlock.gif        {
59            System.Console.Write(b[i] + " ");
60        }

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

63}

 

 

转载于:https://www.cnblogs.com/Sangplus/archive/2009/05/28/1491510.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值