Suppose I have a C# struct like this:
[StructLayout(LayoutKind.Explicit)]
struct IMAGE_DOS_HEADER {
[FieldOffset(60)] public int e_lfanew;
}
<
Yes you can do this using reflection.
FieldOffsetAttribute fieldOffset =
(FieldOffsetAttribute)typeof(IMAGE_DOS_HEADER)
.GetField("e_lfanew")
.GetCustomAttributes(
typeof(FieldOffsetAttribute),
true
)[0];
Console.WriteLine(fieldOffset.Value);
You can even turn this into a nice method:
static int FieldOffset(string fieldName) {
if (typeof(T).IsValueType == false) {
throw new ArgumentOutOfRangeException("T");
}
FieldInfo field = typeof(T).GetField(fieldName);
if (field == null) {
throw new ArgumentOutOfRangeException("fieldName");
}
object[] attributes = field.GetCustomAttributes(
typeof(FieldOffsetAttribute),
true
);
if (attributes.Length == 0) {
throw new ArgumentException();
}
FieldOffsetAttribute fieldOffset = (FieldOffsetAttribute)attributes[0];
return fieldOffset.Value;
}
Usage:
Console.WriteLine(FieldOffset("e_lfanew"));