Retrieve the [StructLayout] attribute of a struct

c#, sizeof, struct

Solution

The information in the StructLayout attribute is embedded in the method as IL directives, not as a custom property. To retrieve it, you can use the Type.StructLayoutAttribute Property:

var type = typeof(Entry);
var sla = type.StructLayoutAttribute;

Alternatively, if the struct is under your control you could simply define a Size constant:

[StructLayout(LayoutKind.Explicit, Pack = 1, Size = Entry.Size)]
internal unsafe struct Entry
{
    public const int Size = 22;
    ...

Problem

I would like to fetch the struct size of 22 bytes from the StructLayout applied to the following structure. ``` [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Pack = 1, Size = 22)] internal unsafe struct Entry { [FieldOffset(0)] private fixed char title[14]; [FieldOffset(14)] private readonly int size; [FieldOffset(18)] private readonly int start; } ``` One would advise Marshal.SizeOf but it returns the size of the unmanaged object of 28 bytes which is undesired. ``` int count = Marshal.SizeOf(typeof(Entry)); ``` However, getting this attribute seems not possible as the array 'customAttributes' is always of length 0. ``` var type = typeof(Entry); var customAttributes = type.GetCustomAttributes(typeof(StructLayoutAttribute), true); ``` Any workaround ?

Original source