如何获得固定的缓冲区长度?

How to get fixed buffer length?

有没有办法获取固定大小缓冲区的长度?

类似于:

public struct MyStruct
{
    public unsafe fixed byte buffer[100];

    public int foo()
    {
        return sizeof(buffer); // Compile error.
    }
}

有什么办法可以完成这样的事情吗?

那是一个数组;你可以只使用 .Length.

like in C++, you have to keep size of built-in arrays. Same applies for fixed buffers in C#. This type is comparableinline_array。这为您带来了诸如静态代码检查之类的好处。使用它们有点麻烦,因为它们不是 C# 的第一个 class 功能。因此,最好的解决方案可能是将大小保留为结构的一部分。您可能只需要处理它或使用 collection/C# 的 System.Array。也许另一种解决方案是将固定缓冲区创建为单独的结构,然后将其与其他数据一起作为另一个结构的一部分。

好吧,我晚了 6 年才回答,但我做到了。显然有一个 属性 包含固定缓冲区的长度!这是获取它的简单方法。您需要传递 MyStruct 类型和字段名称:

    public static int GetFixedBufferSize(Type type, string field)
    {
        FieldInfo fi = type.GetField(field);
        object[] attrs = fi.GetCustomAttributes(typeof(FixedBufferAttribute), false);
        if (attribs != null && attribs.Length != 0)
        {
            FixedBufferAttribute attr = (FixedBufferAttribute)attribs[0];
            Console.WriteLine($"{attr.ElementType.Name} {field}[{attr.Length}]");
            return attr.Length;
        };

        throw new Exception("Not a FixedBuffer");
    }

希望这对你有用,我用你的例子试过了,它成功了!