Calculating the byte size of an object

1.7k Views Asked by At

I am beginning to utilise directx, and the slimdx wrapper in c#. For many methods it is necessary to calculate the size of an object, for example in the case of buffers and draw calls. In particular, the "stride" being the number of bytes between successive elements.

So far the data I am passing is a single Vector3, of 12 bytes length. Therefore the size of buffer used is the number of elements * 12. In this simple case its easy to see what the size should be. However, how should I calculate it for more complicated examples? For instance:

struct VertexType
{
    public Vector3 position;
    public Vector4 color;
}

Would this be (12+16) in size? Does the fact it is arranged in a struct add anything to the size of the element?

I have tried using sizeof, but this throws an error stating the object is not of a predetermined size. What would be the correct approach?

1

There are 1 best solutions below

0
On

Try Marshal.SizeOf - http://msdn.microsoft.com/en-us/library/System.Runtime.InteropServices.Marshal.SizeOf(v=vs.110).aspx

using System.Runtime.InteropServices;

VertexType v = new VertexType;
Marshal.SizeOf(typeof(VertexType)); //For the type
Marshal.SizeOf(v); //For an instance