Repository navigation
Description
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
- explicit alignment requirements
- .NET support for a mechanism like Rust's
repr(transparent)
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: 5Alternative 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
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNo status
Activity
dotnet-policy-service commentedon Apr 10, 2024
Tagging subscribers to this area: @dotnet/interop-contrib
See info in area-owners.md if you want to be subscribed.
tannergooding commentedon Apr 11, 2024
I would expect some Roslyn integration to be a baseline requirement. The compiler already special cases
StructLayout,FieldOffset, and several of the otherCompilerServices/InteropServicesattributes 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
LayoutKindis set, thenFieldOffsetwould be blocked from usage since the layout kind isn'tExplicitAt that point, I think it's worth just minimally integrating it like we did for extended
CallConvso that the compiler understands this is the new thing, thatFieldOffsetis 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 haveCallConv*types. You could then have something likeLayoutKindSwiftorLayoutKindTransparentorLayoutKindSequentialand allow them to be combined in interesting ways that the runtime can opt to support. The root attribute could then have the baseline fields likePackandSizethat 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.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
UnmanagedStructLayoutAttributeorInteropStructLayoutAttributeor 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.AaronRobinsonMSFT commentedon Apr 11, 2024
I don't think that is a requirement. We made the transition to
LibraryImportwithout 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.This is something we should consider. I like following the CallConv approach we've developed.
It follows the same pattern as
LibraryImport,DllImport,JSImport,ComImport- it is importing the definition of something from another source.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
UnmanagedStructLayoutAttributebut since it impacts the layout done by the runtime, it didn't seem appropriate.I would prefer to avoid C# concepts in this definition, especially as it relates to types -
UnmanagedCallersOnlyisn'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.jkotas commentedon Apr 11, 2024
There is an unused value in
LayoutKindenum. We can use this unusedLayoutKindenum 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 ofLayoutKind, but that should not be a big deal. As Tanner pointed out, we may want to make Roslyn aware of this anyway.)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.
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++?
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.)
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.
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.
jkotas commentedon Apr 11, 2024
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).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
UnmanagedLayoutAttributeto 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 withLayoutKind.Unmanaged.AaronRobinsonMSFT commentedon Apr 11, 2024
I fully agree, that is why
UnmanagedLayoutAttributeseems inappropriate. There is no need to imply any association with the C# "unmanaged" concept or the "unmanaged" term inUnmanagedCallersOnly. 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 likeValueTypeLayoutseems the most appropriate.jkotas commentedon Apr 11, 2024
ValueTypeLayoutAttributelooks too similar to the existingStructLayoutAttribute. 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 (StructLayoutAttributemade this mistake - it can be used for both structs and non-structs).Maybe
CustomTypeLayoutAttribute? It would pair withLayoutKind.Custom. We have several existingCustomSomethingAttributes in the BCL.hamarb123 commentedon Apr 11, 2024
I think this name is pretty good. I think avoiding
unmanagedin 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.I think it would be great if we could specify an alignment. It would be very useful.
What happens if I do this:
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:
It would be good if we also kept sequential & auto with this feature so they could benefit from new options like alignment.
SingleAccretion commentedon Apr 11, 2024
I will note that the runtime doesn't support alignments larger than 8 bytes (for on-GC-heap objects).
hamarb123 commentedon Apr 11, 2024
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).
Also, this could presumably(?) break some of use who have
AlignOfhelper functions similarly to:If it would break the above, it would be great to get proper
AlignOfAPIs (ideally both generic in Unsafe, and on RuntimeHelpers like with the new SizeOf API) so we can detect it legitimately.AaronRobinsonMSFT commentedon Apr 11, 2024
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
StructLayoutAttributebeing applicable to reference types to be a huge mistake and has only created complexity and almost no practical upside.I have no push back with that name. The
LayoutKind.Customalso seems natural with that name and the intent.44 remaining items
jkoritzinsky commentedon Aug 14, 2025
Looks like this will get in early .NET 11 (due to the dependency on the Roslyn work).
jkoritzinsky commentedon Jan 9, 2026
Reopening to track runtime support for remaining approved layout kinds.
dotnet-policy-service commentedon Apr 13, 2026
Tagging subscribers to this area: @dotnet/interop-contrib
See info in area-owners.md if you want to be subscribed.
Explore independent union case kinds and generated layouts (#10396)
[Java.Interop] Use CStruct and CUnion for JNI layouts (#12984)