C# command to get struct offset?

前端 未结 2 1261
执念已碎
执念已碎 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<T>(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<IMAGE_DOS_HEADER>("e_lfanew"));
    
    0 讨论(0)
  • 2021-02-15 20:03

    Use Marshal.OffsetOf:

    Marshal.OffsetOf(typeof(IMAGE_DOS_HEADER), "e_lfanew")
    
    0 讨论(0)
提交回复
热议问题