C# 缓冲区解释

标签 c# arrays buffer

这可能是一个真正的初学者问题,但我一直在阅读相关内容,并且发现它很难理解。

这是来自 msdn 的示例关于这个主题的页面(稍微小一点)。

using System;

class SetByteDemo
{
    // Display the array contents in hexadecimal.
    public static void DisplayArray(Array arr, string name)
    {
        // Get the array element width; format the formatting string.
        int elemWidth = Buffer.ByteLength(arr) / arr.Length;
        string format = String.Format(" {{0:X{0}}}", 2 * elemWidth);

        // Display the array elements from right to left.
        Console.Write("{0,7}:", name);
        for (int loopX = arr.Length - 1; loopX >= 0; loopX--)
            Console.Write(format, arr.GetValue(loopX));
        Console.WriteLine();
    }

    public static void Main()
    {
        // These are the arrays to be modified with SetByte.
        short[] shorts = new short[2];

        Console.WriteLine("Initial values of arrays:\n");

        // Display the initial values of the arrays.
        DisplayArray(shorts, "shorts");

        // Copy two regions of source array to destination array,
        // and two overlapped copies from source to source.
        Console.WriteLine("\n" +
            "  Array values after setting byte 1 = 1 and byte 3 = 200\n");
        Buffer.SetByte(shorts, 1, 1);
        Buffer.SetByte(shorts, 3, 10);

        // Display the arrays again.
        DisplayArray(shorts, "shorts");
        Console.ReadKey();
    }
}

SetByte 应该很容易理解,但是如果我在执行 SetByte 操作之前打印 Shorts 数组,则数组看起来像这样

{short[2]}
    [0]: 0
    [1]: 0

完成第一个 Buffer.SetByte(shorts, 1, 1); 后,数组变为

{short[2]}
    [0]: 256
    [1]: 0

设置Buffer.SetByte(shorts, 3, 10);后,数组变为

{short[2]}
    [0]: 256
    [1]: 2560

最后,在示例中,他们从右到左打印数组:

0A00 0100

我不明白这是如何工作的,有人可以给我一些有关这方面的信息吗?

最佳答案

Buffer 类允许您像在 c 中使用 void 指针一样操作内存,它就像 memcpy、memset 等的总和,以快速方式操作 .net 上的内存。

当您传递“shorts”数组时,Buffer 类将其“视为”指向四个连续字节(两个 Shorts,每个字节两个字节)的指针:

  |[0][1]|[2][3]|
   short  short

所以未初始化的数组看起来像这样:

 |[0][0]|[0][0]|
  short  short

当您执行 Buffer.SetByte(shorts, 1, 1); 时,您指示 Buffer 类更改字节数组上的第二个字节,因此它将是:

|[0][1]|[0][0]|
 short  short

如果将两个字节 (0x00, 0x01) 转换为短字节,则为 0x0100(请注意,这是一个接一个的两个字节,但顺序相反,这是因为 C# 编译器使用小字节序),或 256

第二行基本上执行相同的操作 Buffer.SetByte(shorts, 3, 10);将第三个字节更改为 10:

|[0][1]|[0][10]|
 short  short

然后 0x00,0x0A 作为短路是 0x0A00 或 2560。

关于C# 缓冲区解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266737/

相关文章:

c# - 在 C# 中处理可以为 null 或数组的 json 类型

c# - 如何在 C# 中全局定义常量(如 DEBUG)

c# - Monitor.TryEnter 不起作用

c# - C#中的日期时间间隔限制

c - 未读取 uart 缓冲区

c++ - 使用 C++-AMP 访问缓冲区

c - 是否可以从缓冲区解析 pcap 数据包

C# 8 基本接口(interface)的默认方法调用解决方法

javascript - 简单求和 ng-repeat 列

php - Mysql_query 查询数组内的所有项目