C#指针*的使用(使用指针复制字节数组)---02

来源:互联网 发布:程序员怎么去找视频 编辑:程序博客网 时间:2024/05/19 13:21

下面的示例使用指针将字节从一个数组复制到另一个使用指针的数组。

此示例使用 unsafe 关键字,它允许在 Copy 方法内使用指针。fixed 语句用于声明指向源数组和目标数组的指针。这将锁定源数组和目标数组在内存中的位置,使其不会因为垃圾回收操作而移动。这些内存块将在fixed 块结束时取消锁定。因为本示例中 Copy 函数使用了unsafe 关键字,它必须使用/unsafe 编译器选项进行编译。

示例

C#
复制
// compile with: /unsafe
C#
复制
[csharp] view plaincopyprint?
  1. class 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. int srcLen = src.Length;
  12. int dstLen = dst.Length;
  13. if (srcLen - srcIndex < count || dstLen - dstIndex < count)
  14. {
  15. throw new System.ArgumentException();
  16. }
  17. // The following fixed statement pins the location of the src and dst objects
  18. // in memory so that they will not be moved by garbage collection.
  19. fixed (byte* pSrc = src, pDst = dst)
  20. {
  21. byte* ps = pSrc;
  22. byte* pd = pDst;
  23. // Loop over the count in blocks of 4 bytes, copying an integer (4 bytes) at a time:
  24. for (int i = 0 ; i < count / 4 ; i++)
  25. {
  26. *((int*)pd) = *((int*)ps);
  27. pd += 4;
  28. ps += 4;
  29. }
  30. // Complete the copy by moving any bytes that weren't moved in blocks of 4:
  31. for (int i = 0; i < count % 4 ; i++)
  32. {
  33. *pd = *ps;
  34. pd++;
  35. ps++;
  36. }
  37. }
  38. }
  39. static void Main()
  40. {
  41. byte[] a = new byte[100];
  42. byte[] b = new byte[100];
  43. for (int i = 0; i < 100; ++i)
  44. {
  45. a[i] = (byte)i;
  46. }
  47. Copy(a, 0, b, 0, 100);
  48. System.Console.WriteLine("The first 10 elements are:");
  49. for (int i = 0; i < 10; ++i)
  50. {
  51. System.Console.Write(b[i] + " ");
  52. }
  53. System.Console.WriteLine("\n");
  54. }
  55. }

输出

The first 10 elements are:0 1 2 3 4 5 6 7 8 9