C#指针*的使用(使用指针复制字节数组)---02
来源:互联网 发布:java web书 编辑:程序博客网 时间:2024/05/29 06:38
下面的示例使用指针将字节从一个数组复制到另一个使用指针的数组。
此示例使用 unsafe 关键字,它允许在 Copy 方法内使用指针。fixed 语句用于声明指向源数组和目标数组的指针。这将锁定源数组和目标数组在内存中的位置,使其不会因为垃圾回收操作而移动。这些内存块将在fixed 块结束时取消锁定。因为本示例中 Copy 函数使用了unsafe 关键字,它必须使用/unsafe 编译器选项进行编译。
示例
C#
复制
// compile with: /unsafe
C#
复制
class TestCopy{ // The unsafe keyword allows pointers to be used within the following method: 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 System.ArgumentException(); } int srcLen = src.Length; int dstLen = dst.Length; if (srcLen - srcIndex < count || dstLen - dstIndex < count) { throw new System.ArgumentException(); } // The following fixed statement pins the location of the src and dst objects // in memory so that they will not be moved by garbage collection. fixed (byte* pSrc = src, pDst = dst) { byte* ps = pSrc; byte* pd = pDst; // Loop over the count in blocks of 4 bytes, copying an integer (4 bytes) at a time: for (int i = 0 ; i < count / 4 ; i++) { *((int*)pd) = *((int*)ps); pd += 4; ps += 4; } // Complete the copy by moving any bytes that weren't moved in blocks of 4: for (int i = 0; i < count % 4 ; i++) { *pd = *ps; pd++; ps++; } } } static void Main() { 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); System.Console.WriteLine("The first 10 elements are:"); for (int i = 0; i < 10; ++i) { System.Console.Write(b[i] + " "); } System.Console.WriteLine("\n"); }}
输出
The first 10 elements are:0 1 2 3 4 5 6 7 8 9
- C#指针*的使用(使用指针复制字节数组)---02
- C#指针*的使用(使用指针复制字节数组)---02
- 使用指针复制字节数组
- 数组指针、指针数组、指向指针的指针使用总结
- c#中使用数组指针
- 数组指针的使用
- 指针数组与数组指针的使用
- 指针数组和数组指针的使用
- 指针数组和数组指针的使用
- 数组指针和指针数组的使用
- 指针数组和数组指针的使用
- 指针数组和数组指针的使用
- 指针数组和数组指针的使用
- 数组指针的使用要点
- java 指针 数组的使用
- 指针数组的使用总结
- java 指针 数组的使用
- 函数指针数组的使用
- (SQL语句)检测sql语句执行的效率(耗时)
- java基础知识08
- C#中指针*的使用(unsafe关键字与fixed 语句)---01
- 第十一章:线程池
- js判断润年,计算某一天几个月or几天后是什么时间
- C#指针*的使用(使用指针复制字节数组)---02
- 不带缓存的I/O和标准(带缓存的)I/O(经典)
- 1+1/2+1/4+1/6+....+1/100
- 一步一步往上爬 学习毕老师java视频的第01.02天
- 关于VS2010不能正常显示asp.net的网页项目的问题
- Eclipse快捷键大全
- js 区分鼠标点的是左键还是右键以及屏蔽右键菜单
- 我的分层
- [IT 男人帮 11-11] 毕业一年写给自己的警戒书-褪墨