J. Kim
J. Kim

Reputation: 39

Struct is getting wrong size

I am now trying to get the Struct size of C #. However, the size of the struct shown below is 16 bytes. It is normal that 58byte should come out, but I do not know what is wrong.

[Serializable, StructLayout(LayoutKind.Sequential,Pack =1)]
public struct LOBBY_USER_INFO 
{
    LOBBY_DATA_HEADER ldh;
    int userPixNumber; //4byte
    byte[] userID; //50byte

    public LOBBY_USER_INFO(int data_size, int userPixNumber, string userID) 
    {

        this.ldh.data_size = data_size;
        this.userID = new byte[50];
        this.userID = Encoding.UTF8.GetBytes(userID);
        this.userPixNumber = userPixNumber;
    }
}

int size = Marshal.SizeOf(typeof(LOBBY_USER_INFO));

Upvotes: 0

Views: 325

Answers (2)

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

In addition to Dmitry Bychenko's answer:

If you want the userID array to be marshaled within the structure, use MarshalAs(UnmanagedType.ByValArray, ...) attribute:

[Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LOBBY_USER_INFO
{
    //LOBBY_DATA_HEADER ldh;
    int userPixNumber; //4byte
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
    byte[] userID; //50byte
}

// .................
int size = Marshal.SizeOf(typeof(LOBBY_USER_INFO));
// size is 54 now

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

byte[] is a class not a struct, so sizeof(byte[]) is the size of reference (pointer) which is 4 or 8 bytes (32 or 64 bits)

Upvotes: 3

Related Questions