C# command to get struct offset?

前端 未结 2 1268
执念已碎
执念已碎 2021-02-15 19:25

Suppose I have a C# struct like this:

[StructLayout(LayoutKind.Explicit)]
struct IMAGE_DOS_HEADER {
    [FieldOffset(60)] public int e_lfanew;
}
<
2条回答
  •  醉酒成梦
    2021-02-15 19:53

    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"));
    

提交回复
热议问题