Skip to content

API Proposal: Add alignment to StructLayout #9089

@xoofx

Description

@xoofx

Currently with [StructLayout] we can define both the size (via Size field) and the field packing (via Pack field) . Unfortunately, it doesn't cover the case in C++ where you can have an alignment attribute directly on the struct that indicates how this struct should be aligned when used for example in another struct.

This is actually quite a limitation when for example you want to have a struct that maps to a vector SIMD intrinsic as their natural alignment is usually not the alignment of the component. For a Vector4f, the align of this struct in C# would be sizeof(float), while it would be 4xsizeof(float) for the intrinsic.

This could also help in regular interop scenarios where this align attribute is actually specified on the C++ struct.

Note: As this is an API change but most of the work would be in coreclr, not sure if this is the right place to post this instead of corefx. Let me know if you can move it there.

StructLayout.Align

The proposal is to add a new property Align on StructLayout:

 public sealed class StructLayoutAttribute : Attribute
{
    ...
    public int Align;
    ...
}

By default, the alignment is 0, meaning that it will take the natural alignment of the struct (which is the default today). Otherwise it will take the alignment specified by this field.

cc: @jkotas @CarolEidt

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions