Skip to content

Expose an attribute to allow sizing a fixed sized buffer based on type and element count. #12320

Description

@tannergooding

Today, C# emulates fixed-sized buffers by emitting an explicitly sized struct with a single-field. This works decently enough for primitive types which have a constant size across varying platforms, but it does not work well for user-defined structs which may have different packing or different sizes across varying platforms/architectures.

This can be worked around by explicitly declaring a struct that contains x elements of type T, but this can quickly become overly verbose for fixed-sized buffers that contain many elements (e.g. 128 or even 1025).

I propose we expose an attribute that the VM will recognize and which it will use to dynamically size the type based on the information given.

This will allow a user to define something similar to:

public struct DXGI_RGB
{
    public float Red;
    public float Green;
    public float Blue;
}

public struct DXGI_GAMMA_CONTROL
{
    public DXGI_RGB Scale;
    public DXGI_RGB Offset;
    public _GammaCurve_e__FixedBuffer GammaCurve;    // DXGI_RGB[1025]

    [FixedSizedBuffer(typeof(DXGI_RGB), count: 1025)]
    public struct _GammaCurve_e__FixedBuffer
    {
        private DXGI_RGB e0;

        public ref DXGI_RGB this[int index] => ref AsSpan()[index];

        public Span<DXGI_RGB> AsSpan() => MemoryMarshal.CreateSpan(ref e0, 1025);
    }
}

This would also be beneficial for the fixed-sized-buffers proposal in C#, as it would avoid the metadata bloat problem that exists: https://github.com/dotnet/csharplang/blob/725763343ad44a9251b03814e6897d87fe553769/proposals/fixed-sized-buffers.md

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions