Search code examples
c#openglstructsizeofvertex-buffer

Whats the sizeof C# structs for vertex representation in OpenGL (OpenTK)?


currently I'm experimenting with OpenGL (via OpenTK) in C#. I looked at several tutorials and often found, that structs are used to describe a vertex.

struct ColoredVertex
{
    public const int Size = (3 + 4) * 4;

    private readonly Vector3 position;
    private readonly Color4 color;

    public ColoredVertex(Vector3 position, Color4 color)
    {
        this.position = position;
        this.color = color;
    }
}

Then I asked myself why they don't use the sizeof() function of C# and noticed, that it doesn't work on structs because of packing or so.

Okay, but isn't this an issue? If I'm thinking correct, the usage of GL.BufferData to upload the array of ColoredVertex to the GPU with a stride of ColoredVertex.Size could cause wrong data interpretation because the CLR might decide to use a different packing for the structure array, am I right?

So what would be the best way to inform OpenGL about the Vertex layout? The use of Marshal.sizeof or an unsafe-block like the compiler suggests?

CS0233  'Vec3' does not have a predefined size, therefore sizeof can
only be used in an unsafe context (consider using
System.Runtime.InteropServices.Marshal.SizeOf)

Solution

  • Apply the [StructLayout(LayoutKind.Explicit)] attribute to the struct and then apply [FieldOffset(n)] to each field to position it at your selected byte position, n.

    This gives you fine-grained control of position, and since the sizes of primitive types in C# do not depend on the platform (64 vs 32 bit) that also tells you the size and complete layout.