Structure size

You can get the size of the structure using


Marshal.SizeOf(typeof(mystruct));

Is it possible to get the size of part of the structure (for example, I pass the function of the last field of the structure and returns the sum of the sizes of the previous fields)? As far as I understand, is it possible to use reflection?

+3
source share
3 answers
[StructLayout(LayoutKind.Explicit)]
public struct SomeStruct
{
    [FieldOffset(0)]
    public byte b1;
    [FieldOffset(3)]
    public byte b2;
    [FieldOffset(7)]
    public int i1;
    [FieldOffset(12)]
    public int i2;
}

class Program
{
    static FieldOffsetAttribute GetFieldOffset(string fieldName)
    {
        return (FieldOffsetAttribute)typeof(SomeStruct)
            .GetField(fieldName)
            .GetCustomAttributes(typeof(FieldOffsetAttribute), false)[0];
    }

    static void Main(string[] args)
    {
        var someStruct = new SomeStruct { b1 = 1, b2 = 2, i1 = 3, i2 = 4 };

        Console.WriteLine("field b1 offset: {0}", GetFieldOffset("b1").Value);
        Console.WriteLine("field b2 offset: {0}", GetFieldOffset("b2").Value);
        Console.WriteLine("field i1 offset: {0}", GetFieldOffset("i1").Value);
        Console.WriteLine("field i2 offset: {0}", GetFieldOffset("i2").Value);

        Console.ReadLine();
    }
}

Cachet: field b1 offset: 0 field b2 offset: 3 field i1 offset: 7 offset field i2: 12

+3
source

.NET. JIT , , . , . , Marshal.SiseOf() . Marshal.StructureToPtr().

: , , Reflection. .

+2

Well, I'm not sure, but I think this is not possible due to possible optimization and alignment issues.

+1
source

Source: https://habr.com/ru/post/1729549/


All Articles