tags:

views:

46

answers:

3

In Java, a byte or short is stored in the JVM's 'natural' word length, i.e. for the most part, 32-bits. An exception would be an array of bytes, where each byte occupies a byte of memory.

Does the CLR do the same thing?

If it does do this, in what situations are there exceptions to this? E.g. How much memory does this occupy?

struct MyStruct
{
    short s1;
    short s2;
}
+3  A: 

Although it's not really intended for this purpose, and may at times give slightly different answers (because it's thinking about things from a Marshalling point of view, not a CLR internal structures point of view), Marhsal.SizeOf can give an answer:

System.Runtime.InteropServices.Marshal.SizeOf(typeof(MyStruct))

In this case, it answers 4. (i.e. the shorts are being stored as shorts). Please note that this is an implementation detail, so the answer today should not be relied upon for any purpose.

Damien_The_Unbeliever
I wonder what Marshal.SizeOf(typeof(int)) does
izb
Note that the layout, especially for marshalling, can be modified with `StructLayout`.
OregonGhost
+1  A: 

The CLR does to some extent pack members of the same size. It does pack arrays, and I would expect your example structure to take up four bytes on any platform.

Exactly which types are packed and how depends on the CLR implementation and the current platform. The rules are not strictly defined, so that the CLR has some freedom to rearrange the members to store them in the most efficient manner.

Guffa
+2  A: 

It is actually the job of the JIT compiler to assign the memory layout of classes and structures. The actual layout is not discoverable in any way (beyond looking at the generated machine code), a [StructLayout] attribute is required to marshal the object to a known layout. The JIT takes advantage of this by re-ordering fields to keep them aligned and minimize the allocation size.

There will be no surprises in the struct you quoted, the fields are already aligned on any current CPU architecture that can execute managed code. The size of value types is guaranteed by the CLI, a short always takes 16 bits. Your structure will take 32 bits.

Hans Passant
+1 for mentioning `StructLayout`, which is the single most important thing if you want to do interop (which is where you *need* to specify the exact layout).
OregonGhost