Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshal.SizeOf of a structure showing wrong output [duplicate]

Here's my code:

struct abc
{
    short a;
    byte b;
    int c;
}

When I use:

Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(typeof(abc)));

It shows: 8 whereas it should show: 7 because in my machine: byte: 1, short:2, int:4 bytes respectively.

Why is it happening?

If it is happening due to padding, how to disable the padding while reading the size of the structure? Because i need the exact size of the structure in bytes. It's important.

like image 573
Sayan Sen Avatar asked Oct 18 '25 13:10

Sayan Sen


1 Answers

It's showing 8 because of structure member alignment rules.

If you want to set your struct as unaligned, you need to use StructLayout with the Pack = 1 attribute like so:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct abc
{
    short a;
    byte b;
    int c;
}

This should output 7.

like image 164
Koby Douek Avatar answered Oct 21 '25 02:10

Koby Douek