Skip to content

[API Proposal]: New attribute for interop-specific struct concerns #100896

Open

Description

@jkoritzinsky

Background and motivation

.NET's struct layout system is quite extensive, but there are still some cases it does not cover that are relevant in interop scenarios at the language/runtime boundary.

In particular, we've seen requests for features like

With Swift Interop, we have a need to represent generic structs with correct Swift layouts, but we don't have a way to represent the Swift layout accurately in the general case. In the non-general case, we can represent it with an explicit StructLayout.Size element, but we can't do that for generics.

For all of these cases, we'd like to extend the StructLayoutAttribute to handle these cases. However, we can't extend that attribute as it's a pseudo-attribute that maps directly to metadata. Instead, we propose adding a new attribute, only usable on struct types, that's intended to encompass all future layout features, as well as the existing layout features provided by StructLayoutAttribute.

As part of the implementation, we plan to introduce a simple source-generator to generate the corresponding StructLayoutAttribute on the type that has our new attribute applied. To ensure that we don't accidentally make types non-blittable, we'll lower the attribute such that CharSet = CharSet.Unicode in all cases.

In the future, we may extend this attribute to also be the "trigger" attribute for an interop source generator to generate a marshaller for a given struct type.

To limit the scope of this feature, we plan to start with only the feature required by Swift interop:

  • Provide a mechanism to not include trailing padding in the .NET struct's size for struct types.

Like the LayoutKind.Sequential support for structs in the runtime, we won't support these new layout requirements for any structs that (recursively) contain reference type fields.

API Proposal

namespace System.Runtime.InteropServices
{
    public enum LayoutKind
    {
        Custom
    }

    [AttributeUsage(AttributeTargets.Struct)]
    public sealed class CustomLayoutAttribute : Attribute
    {
        public CustomLayoutAttribute(CustomLayoutKind kind) {}
        
        // Only valid for CustomLayoutKind.SwiftEnum
        public int RequiredDiscriminatorBits { get; set; }
    }

    public enum CustomLayoutKind
    {
        Sequential, // C-style struct
        Union, // C-style union
        SwiftStruct, // Swift struct
        SwiftEnum // Swift enumeration
    }
}

namespace System.Runtime.InteropServices.Swift
{
    // Represents a pointer to a Swift object (for the purposes of calculating spare bits)
    public readonly unsafe struct SwiftObject
    {
        // Would be implemented to mask out the spare bits
        public void* Value { get; }
    }

    // Represents a bool value in Swift (for the purposes of calculating spare bits)
    public readonly unsafe struct SwiftBool
    {
        // Would be implemented to mask out the spare bits
        // or assign while preserving spare bits
        public bool Value { get; }
    }
}

API Usage

[StructLayout(LayoutKind.Custom)]
[CustomLayout(CustomLayoutKind.SwiftStruct)]
public struct InnerStruct
{
     public short F0; // offset 0
     public sbyte F1; // offset 2
}

[StructLayout(LayoutKind.Custom)]
[CustomLayout(CustomLayoutKind.SwiftStruct)]
public struct OuterStruct
{
    public ulong F0; // offset 0
    public long F1; // offset 8
    public InnerStruct F2; // offset 16
    public sbyte F3; // offset 19
}

[StructLayout(LayoutKind.Custom)]
[CustomLayout(CustomLayoutKind.SwiftEnum, RequiredDescriminatorBits = 1)]
public struct MyOptional<T> where T : unmanaged
{
    [StructLayout(LayoutKind.Custom)]
    [CustomLayout(CustomLayoutKind.SwiftStruct)]
    private struct Some_Payload
    {
          public T Value;
    }

    private Some_Payload Some;

    // An API surface to describe the different cases and provide a C# API around accessing them, out of the scope of this API proposal
}


[StructLayout(LayoutKind.Custom)]
[CustomLayout(CustomLayoutKind.SwiftEnum, RequiredDescriminatorBits = 1)]
public struct ParsedResult
{
     [StructLayout(LayoutKind.Custom)]
     [CustomLayout(CustomLayoutKind.SwiftStruct)]
     private struct ParsedObject_Payload
     {
            public SwiftPointer payload_0;
     }
     [StructLayout(LayoutKind.Custom)]
     [CustomLayout(CustomLayoutKind.SwiftStruct)]
     private struct ParsedBool_Payload
     {
            public SwiftBool payload_0;
     }

     private ParsedObject_Payload ParsedObject;
     private ParsedBool_Payload SwiftBool;
    // An API surface to describe the different cases and provide a C# API around accessing them, out of the scope of this API proposal
}

API review notes below: #100896 (comment)

Alternative Designs

We could provide a set of layout primitives instead of a set of well-known layouts (the original proposal). However, we'd then have to handle all possible combinations of these primitives or block them to only the valid combinations to match our equivalent support in the current proposal.

We could go further than the original proposal and have a mechanism for specifying OS/Arch-specific layout and ABI parameter passing rules in attributes. This design would allow the runtime to be entirely out of the business of layout and ABI handling other than reading the attributes. This design has a few problems through: We'd need to consider how to provide/validate the provided options. The code-gen backends would need to respect this information (and reading from custom attributes is expensive). Generics would also be a problem in this design space.

Original API Proposal

API Proposal

namespace System.Runtime.InteropServices;

[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
public sealed class ImportedStructAttribute : Attribute
{
    // StructLayoutAttribute matching members, excluding CharSet.
    public int Pack { get; set; }
    public int Size { get; set; }
    public ImportedStructAttribute(LayoutKind layoutKind);
    public LayoutKind LayoutKind { get; set; }
    // New member for Swift layout requirements
    public bool PadSizeToAlignment { get; set; }
}

API Usage

[ImportedStruct(LayoutKind.Sequential, PadSizeToAlignment = false)]
struct SwiftOptionalLike<T>
{
    T value;
    byte isNull;
}

Console.WriteLine(Unsafe.SizeOf<SwiftOptionalLike<int>>()); // Output: 5

Alternative Designs

We could provide a dedicated attribute for the Swift scenario.

We could have Roslyn support lowering the StructLayoutAttribute-corresponding members to metadata instead of introducing a source generator.

We could skip including the StructLayoutAttribute APIs and have the attributes represent separate concepts.

We could add new members to StructLayoutAttribute and require all compilers to recognize when new members are specified and not remove the attribute (and still lower the original members to metadata). This option is very expensive.

Risks

No response

Activity

  1. added
    api-suggestion
    on Apr 10, 2024
  2. dotnet-policy-service commented on Apr 10, 2024

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/interop-contrib
    See info in area-owners.md if you want to be subscribed.

  3. added
    untriaged
    on Apr 10, 2024
  4. tannergooding commented on Apr 11, 2024

    @tannergooding
    Member

    We could have Roslyn support lowering the StructLayoutAttribute-corresponding members to metadata instead of introducing a source generator.

    I would expect some Roslyn integration to be a baseline requirement. The compiler already special cases StructLayout, FieldOffset, and several of the other CompilerServices/InteropServices attributes including when specifying them is legal or not.

    If we are going to have this work as pay for play where we only go look at the extended attributes if a particular LayoutKind is set, then FieldOffset would be blocked from usage since the layout kind isn't Explicit

    At that point, I think it's worth just minimally integrating it like we did for extended CallConv so that the compiler understands this is the new thing, that FieldOffset is allowed with the new thing, and that there is a general extensibility model for representing this data.

    Theoretically we could just have something like LayoutKind* types, much as we have CallConv* types. You could then have something like LayoutKindSwift or LayoutKindTransparent or LayoutKindSequential and allow them to be combined in interesting ways that the runtime can opt to support. The root attribute could then have the baseline fields like Pack and Size that every type has. -- Just as a hypothetical that loosely correlates to how we've done other things, this isn't necessarily a good idea or the right direction for type layout.

    public sealed class ImportedStructAttribute : Attribute

    I'm not a huge fan of this name and don't think it's necessarily obvious what it means.

    Could we define it as UnmanagedStructLayoutAttribute or InteropStructLayoutAttribute or something along those lines instead, perhaps? Make it clear its only works with "unmanaged" types, is primarily for use in interop scenarios, is defining the layout of the type, etc.

  5. AaronRobinsonMSFT commented on Apr 11, 2024

    @AaronRobinsonMSFT
    Member

    I would expect some Roslyn integration to be a baseline requirement.

    I don't think that is a requirement. We made the transition to LibraryImport without any deep Roslyn integration. If however you are simply referring to an Analyzer/Fixer/Source generator that is something I could understand. I'm still not sure it is needed, but it depends on how broadly we expect the attribute to be used in v1.

    Theoretically we could just have something like LayoutKind* types, much as we have CallConv* types.

    This is something we should consider. I like following the CallConv approach we've developed.

    I'm not a huge fan of this name and don't think it's necessarily obvious what it means.

    It follows the same pattern as LibraryImport, DllImport, JSImport, ComImport - it is importing the definition of something from another source.

    Could we define it as UnmanagedStructLayoutAttribute or InteropStructLayoutAttribute or something along those lines instead, perhaps?

    These are not appropriate in this case since the values here will be reflected in both the managed type layout itself and not just at the interop boundary. We did consider UnmanagedStructLayoutAttribute but since it impacts the layout done by the runtime, it didn't seem appropriate.

    Make it clear its only works with "unmanaged" types,

    I would prefer to avoid C# concepts in this definition, especially as it relates to types - UnmanagedCallersOnly isn't about types so that works for me. My preference would be using "ValueType" rather than "Unmanaged". I think the "Import" term is something which is consistent with our other scenarios and should be used to align with the pattern.

  6. jkotas commented on Apr 11, 2024

    @jkotas
    Member

    There is an unused value in LayoutKind enum. We can use this unused LayoutKind enum value to mean "look at the new attribute for the layout spec". It is similar to the approach we have used for CallConv where we have mapped an unused value to mean "look at the modops". (It would require a Roslyn change to relax the validation of LayoutKind, but that should not be a big deal. As Tanner pointed out, we may want to make Roslyn aware of this anyway.)

    With Swift Interop, we have a need to represent generic structs with correct Swift layouts

    There are number of other issues with generics support in Swift interop. Unless we have a solution for how to make generics work well with Swift interop end-to-end, solving the struct layout issue is not that interesting.

    Size

    I think it is a questionable property. As far as I know, there is no equivalent in C/C++.

    Also, would it make more sense to allow specifying alignment, to better match how one can control layout in C/C++?

    PadSizeToAlignment

    Is this all that is required to express layout of all possible Swift structs? Is there a prior art for expressing the Swift layout struct rules in clang/C++? (I am not sure whether I like inventing names like this for language-specific layout algorithms.)

    that FieldOffset is allowed with the new thing

    Why would we want to allow FieldOffset with the new thing? FieldOffset is problematic concept (except when used with offset 0) - I believe that you made this point earlier.

    we could just have something like LayoutKind* types, much as we have CallConv* types

    The CallConv... types exist to allow encoding the calling convention in function pointers. It is not possible to use attributes for function pointers. I think attribute works just fine for encoding type layout.

  7. jkotas commented on Apr 11, 2024

    @jkotas
    Member

    We made the transition to LibraryImport without any deep Roslyn integration.

    Nit: I agree that LibraryImport does not have deep integration with Roslyn. However, we have made changes in Roslyn to make it work well (e.g. relaxed rules for partial).

    We did consider UnmanagedStructLayoutAttribute but since it impacts the layout done by the runtime, it didn't seem appropriate.

    I would expect this to be useful for controlling struct layout in general, not limited to structs imported from other languages. My name choice would be UnmanagedLayoutAttribute to make it as general as possible ("unmanaged" in this context means "not auto-managed by the runtime"). If you take my other suggestions to reuse unused LayoutKind value, the attribute can pair with LayoutKind.Unmanaged.

  8. AaronRobinsonMSFT commented on Apr 11, 2024

    @AaronRobinsonMSFT
    Member

    I would expect this to be useful for controlling struct layout in general, not limited to structs imported from other languages.

    I fully agree, that is why UnmanagedLayoutAttribute seems inappropriate. There is no need to imply any association with the C# "unmanaged" concept or the "unmanaged" term in UnmanagedCallersOnly. Instead I think indicating what is being customized, a "ValueType", is the ideal term. The "Import" term was used since we assumed the majority of this customization would be in service of defining types from other systems. Your remarks about a "general purpose" mechanism is compelling so calling this something like ValueTypeLayout seems the most appropriate.

  9. jkotas commented on Apr 11, 2024

    @jkotas
    Member

    ValueTypeLayoutAttribute looks too similar to the existing StructLayoutAttribute. We may want something more distinct, and we may want to avoid coupling the name to value types in case we need to use it for more than value types in future (StructLayoutAttribute made this mistake - it can be used for both structs and non-structs).

    Maybe CustomTypeLayoutAttribute? It would pair with LayoutKind.Custom. We have several existing CustomSomethingAttributes in the BCL.

  10. hamarb123 commented on Apr 11, 2024

    @hamarb123
    Contributor

    Maybe CustomTypeLayoutAttribute? It would pair with LayoutKind.Custom. We have several existing CustomSomethingAttributes in the BCL.

    I think this name is pretty good. I think avoiding unmanaged in the name is a good idea - I thought we would make it not work with managed structs when the name was suggested because that's what it implies.

    Also, would it make more sense to allow specifying alignment, to better match how one can control layout in C/C++?

    I think it would be great if we could specify an alignment. It would be very useful.

    [ImportedStruct(LayoutKind.Sequential, PadSizeToAlignment = false)]
    struct SwiftOptionalLike<T>
    {
        T value;
        byte isNull;
    }
    
    Console.WriteLine(Unsafe.SizeOf<SwiftOptionalLike<int>>()); // Output: 5

    What happens if I do this:

    SwiftOptionalLike<int>[] array = new SwiftOptionalLike<int>[5];
    Span<SwiftOptionalLike<int>> span = array;
    span[1].Value = 5; //is it misaligned? (and do we care or not?) or is sizeof is wrong and cannot be used anymore for this? or do we just disallow this entirely somehow?

    Why would we want to allow FieldOffset with the new thing? FieldOffset is problematic concept (except when used with offset 0) - I believe that you made this point earlier.

    I'd tend to agree that allowing FieldOffset it probably not a good idea, unless we have a good reason to combine explicit layout with the additional features this new system may provide.

    Here's 2 useful layouts I'd like to see that we could potentially make with this feature:

    • transparent layout
    • union layout (something along the lines of: first field is identifier, and the rest are laid out overlapped by the runtime automatically to minimise the size whilst keeping managed & unmanaged sections separate - I described such an idea here also in more detail)

    It would be good if we also kept sequential & auto with this feature so they could benefit from new options like alignment.

  11. SingleAccretion commented on Apr 11, 2024

    @SingleAccretion
    Contributor

    alignment control

    I will note that the runtime doesn't support alignments larger than 8 bytes (for on-GC-heap objects).

  12. hamarb123 commented on Apr 11, 2024

    @hamarb123
    Contributor

    I will note that the runtime doesn't support alignments larger than 8 bytes (for on-GC-heap objects).

    Indeed, that part, if approved, would presumably just be delayed until the runtime could support it (since I assume there's no fundamental reason why it couldn't work).

    [ImportedStruct(LayoutKind.Sequential, PadSizeToAlignment = false)]
    struct SwiftOptionalLike<T>
    {
        T value;
        byte isNull;
    }
    
    Console.WriteLine(Unsafe.SizeOf<SwiftOptionalLike<int>>()); // Output: 5

    Also, this could presumably(?) break some of use who have AlignOf helper functions similarly to:

    struct AlignHelper<T>
    {
        T value;
        byte field;
    }
    
    static unsafe int AlignOf<T>() => sizeof(AlignHelper<T>) - sizeof(T);
    
    Console.WriteLine(AlignOf<SwiftOptionalLike<int>>()); //would this produce what we expect for alignment?
    //it relates to the question I asked about spans earlier

    If it would break the above, it would be great to get proper AlignOf APIs (ideally both generic in Unsafe, and on RuntimeHelpers like with the new SizeOf API) so we can detect it legitimately.

  13. AaronRobinsonMSFT commented on Apr 11, 2024

    @AaronRobinsonMSFT
    Member

    we may want to avoid coupling the name to value types in case we need to use it for more than value types in future

    I thought about this when Jeremy first suggested the idea - "Would we ever want this for reference types?". I don't think I have the imgination to come up with a scenario where we would want to play layout games with reference types. Not pushing back on the suggestion, but is there an obvious case where it would be compelling? I personally find the StructLayoutAttribute being applicable to reference types to be a huge mistake and has only created complexity and almost no practical upside.

    Maybe CustomTypeLayoutAttribute? It would pair with LayoutKind.Custom. We have several existing CustomSomethingAttributes in the BCL.

    I have no push back with that name. The LayoutKind.Custom also seems natural with that name and the intent.

  14. 44 remaining items

  15. jkoritzinsky commented on Aug 14, 2025

    @jkoritzinsky
    MemberAuthor

    Looks like this will get in early .NET 11 (due to the dependency on the Roslyn work).

  16. modified the milestones: 10.0.0, 11.0.0 on Aug 14, 2025
  17. jkoritzinsky commented on Jan 9, 2026

    @jkoritzinsky
    MemberAuthor

    Reopening to track runtime support for remaining approved layout kinds.

  18. dotnet-policy-service commented on Apr 13, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/interop-contrib
    See info in area-owners.md if you want to be subscribed.

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

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Runtime.InteropServices

Type

No type

Projects

  • Status
    No status

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions