This simple program:
namespace ConsoleApp1;
using System.Data;
using System.Reflection;
using System.Runtime.InteropServices;
internal class Program {
[StructLayout(LayoutKind.Sequential, Pack=4)]
public sealed class Data {
}
static void Main(string[] args) {
StructLayoutAttribute layout = typeof(Data).GetCustomAttribute<StructLayoutAttribute>() ??
throw new NoNullAllowedException("layout");
}
}
throws. Why can't I reflect on this attribute? I need to be able to do this for a dual-purpose case where the C# class needs to be serialised in native pinvoke, but also a separate code generator needs to be able to extract the struct pack value.
StructLayout
is a pseudo-attribute.
"These attributes are perceived and treated by the compilers as other custom attributes are, but they are never emitted as such. Instead of emitting these attributes, the metadata emission API sets specific values of the metadata" ( Serge Lidin (2014). .NET IL Assembler)
The way to get its value with reflection is via the StructLayoutAttribute
property on Type
:
StructLayoutAttribute layout = typeof(Data).StructLayoutAttribute;