Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of struct C#

Tags:

c#

struct

I'm new in C#.
I'm trying to understand why the struct size is grow.
I.e:

struct Test
{
    float x;
    int y;
    char z;
}

size of Test struct is actually 10 bytes (float=4, int=4, char=2).
But when i tried to get the sizeof struct with Marshal.SizeOf(..) method i got 12.
In C++ i did pragma pack(1) to prevent this but how can i do it in C#?

Another question:
When i tried to convert the Test struct to byte array if the struct isn't [Serialize] i got byte array with size 12 bytes as excepted (or not), but if the struct is [Serialize] i got byte array with size of 170 bytes, why its happend?
Thanks! :)

like image 240
Evyatar Avatar asked Dec 25 '22 08:12

Evyatar


1 Answers

This

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TestStruct
{
    float x;
    int y;
    char z;
}

will give a Marshal.SizeOf() == 9, because Marshal.SizeOf(typeof(char)) == 1 for strange historical reasons.

BUT

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]

with this you'll get Marshal.SizeOf() == 10

like image 56
xanatos Avatar answered Jan 03 '23 19:01

xanatos