本文共 2672 字,大约阅读时间需要 8 分钟。
缓冲区
是内存中的一组字节序列,缓冲
是用来处理落在内存中的数据,.NET 缓冲
指的是处理 非托管内存
中的数据,用 byte[]
来表示。
当你想把数据写入到内存或者你想处理非托管内存中的数据,可以使用 .NET 提供的 System.Buffer
类,这篇文章就来讨论如何使用 Buffer。
Buffer 类包含了下面几个方法:
BlockCopy(Array, Int32, Array, Int32)
用于将指定位置开始的 原数组 copy 到 指定位置开始的 目标数组。
ByteLength(Array)
表示数组中 byte 字节的总数。
GetByte(Array, Int32)
在数组一个指定位置中提取出一个 byte。
SetByte(Array, Int32, Byte)
在数组的一个指定位置中设置一个 byte。
MemoryCopy(Void*, Void*, Int64, Int64)
从第一个源地址上copy 若干个byte 到 目标地址中。
在了解 Buffer 之前,我们先看看 Array 类,Array 类中有一个 Copy()
方法用于将数组的内容 copy 到另一个数组中,在 Buffer 中也提供了一个类似的 BlockCopy()
方法和 Array.Copy()
做的一样的事情,不过 Buffer.BlockCopy()
要比 Array.Copy()
的性能高得多,原因在于前者是按照 byte 拷贝,后者是 content 拷贝。
你可以利用 Buffer.BlockCopy()
方法 将源数组的字节 copy 到目标数组,如下代码所示:
static void Main(){ short [] arr1 = new short[] { 1, 2, 3, 4, 5}; short [] arr2 = new short[10]; int sourceOffset = 0; int destinationOffset = 0; int count = 2 * sizeof(short); Buffer.BlockCopy(arr1, sourceOffset, arr2, destinationOffset, count); for (int i = 0; i < arr2.Length; i++) { Console.WriteLine(arr2[i]); } Console.ReadKey();}
如果没看懂上面输出,我稍微解释下吧,请看这句:int count = 2 * sizeof(short)
表示从 arr1 中 copy 4个字节到 arr2 中,而 4 byte = 2 short
,也就是将 arr1 中的 {1,2}
copy 到 arr2 中,对吧。
要想获取数组中的字节总长度,可以利用 Buffer 中的 ByteLength 方法,如下代码所示:
static void Main(){ short [] arr1 = new short[] { 1, 2, 3, 4, 5}; short [] arr2 = new short[10]; Console.WriteLine("The length of the arr1 is: {0}", Buffer.ByteLength(arr1)); Console.WriteLine("The length of the arr2 is: {0}", Buffer.ByteLength(arr2)); Console.ReadKey();}
从图中可以看出,一个 short 表示 2 个 byte, 5个 short 就是 10 个 byte,对吧,结果就是 short [].length * 2
,所以 Console 中的 10 和 20 就不难理解了,接下来看下 Buffer 的 SetByte 和 GetByte 方法,他们可用于单独设置和提取数组中某一个位置的 byte,下面的代码展示了如何使用 SetByte 和 GetByte。
static void Main() { short[] arr1 = { 5, 25 }; int length = Buffer.ByteLength(arr1); Console.WriteLine("\nThe original array is as follows:-"); for (int i = 0; i < length; i++) { byte b = Buffer.GetByte(arr1, i); Console.WriteLine(b); } Buffer.SetByte(arr1, 0, 100); Buffer.SetByte(arr1, 1, 100); Console.WriteLine("\nThe modified array is as follows:-"); for (int i = 0; i < Buffer.ByteLength(arr1); i++) { byte b = Buffer.GetByte(arr1, i); Console.WriteLine(b); } Console.ReadKey(); }
Buffer 在处理 含有基元类型的一个内存块上 具有超高的处理性能,当你需要处理内存中的数据 或者 希望快速的访问内存中的数据,这时候 Buffer 将是一个非常好的选择。
译文链接:https://www.infoworld.com/article/3587751/how-to-use-the-buffer-class-in-c.html
转载地址:http://fzudi.baihongyu.com/