Error: '<struct>' does not have a predefined size

K

kernel_panic

Consider the following code noting the two uses of sizeof():

unsafe struct A
{
int value;
}

unsafe struct B
{
fixed byte value[sizeof(A)]; // Error: 'A' does not have a
predefined size
}

unsafe struct C
{
static void test()
{
int s = sizeof(A); // legal
}
}

If the second sizeof() is legal, why not the first? It seems like it
should be possible for the compiler to determine the size of struct A
at compile time. Is there something I'm missing?
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

kernel_panic said:
Consider the following code noting the two uses of sizeof():

unsafe struct A
{
int value;
}

unsafe struct B
{
fixed byte value[sizeof(A)]; // Error: 'A' does not have a
predefined size
}

unsafe struct C
{
static void test()
{
int s = sizeof(A); // legal
}
}

If the second sizeof() is legal, why not the first? It seems like it
should be possible for the compiler to determine the size of struct A
at compile time. Is there something I'm missing?

The CLR controls the layout of the struct, so it's not defined at
compile time. The members are padded in the way that is most efficient
for the platform.

Consider a struct like this:

struct A {
byte x, y;
}

As members may be padded into word boundaries (which varies depending on
if the code is run on a 32 bit or 64 bit system), and members may share
a word boundary, the struct can (at least theoretically) take these sizes:

2 bytes (no padding at all)
4 bytes (shared 32 bit boundary)
5 bytes (two 32 bit boundaries, no padding in second)
8 bytes (two 32 bit boundaries)
8 bytes (shared 64 bit boundary)
9 bytes (two 64 bit boundaries, no padding in second)
16 bytes (two 64 bit boundaries)

(The sizes 5 and 9 are probably never used.)
 
K

kernel_panic

The CLR controls the layout of the struct, so it's not defined at
compile time. The members are padded in the way that is most efficient
for the platform.

Ah, that makes sense.

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top