'Pad a struct so its size is a multiple of 16 bytes

I'm trying to have my C# struct match up some complex padding and packing rules.

  • Fields should be aligned on 4 byte boundaries.
  • The entire struct should be a multiple of 16 bytes

Using the StructLayout attribute I can make sure that fields are aligned on 4 byte boundaries.

[StructLayout(LayoutKind.Sequential, Pack=4)]
struct Foo
{
    float a;
    float b;
}

But looking at the other options for the StructLayout attribute I see no options for padding the struct to multiples of 16 bytes. Is there no option for that in C#?

The only option I see is manually set the right size, using the Size property of the StructLayout attribute. But that seems brittle to me. As every time somebody adds a field to this struct they should take care not to forget to update the size.



Solution 1:[1]

After more searching, it indeed does look like I have to manually set the Size and FieldOffset to get to the right packing rules for Constant Buffers in DirectX/HLSL/C# interop code.

In my own project this is even a bit more complex. Since I use source generators to create these structs. But in the end I was able to figure it out. For those interested the source code can be found here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roy T.