Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Marshal.SizeOf() method on a custom struct containing only value types

Tags:

c#

.net

I created a simple struct which consists of two value types.

public struct Identifier
{
    public Guid ID { get; set; }
    public Byte RequestType { get; set; }
}

Then I called Marshal.SizeOf() method on the custom struct Identifier using the following statements.

Identifier i = new Identifier();
Console.WriteLine(Marshal.SizeOf(i));   // output: 20
Console.WriteLine(Marshal.SizeOf(i.GetType()));   // output: 20

Why does Marshal.SizeOf() not return 17? The following instructions show that a Guid object is 16 bytes and a Byte object is 1 byte.

Guid g = Guid.NewGuid();
Console.WriteLine(Marshal.SizeOf(g));   // output: 16
Console.WriteLine(Marshal.SizeOf(g.GetType()));   // output: 16

Byte t = 0;
Console.WriteLine(Marshal.SizeOf(t));   // output: 1
Console.WriteLine(Marshal.SizeOf(t.GetType()));   // output: 1
like image 950
enzom83 Avatar asked Jan 26 '26 12:01

enzom83


2 Answers

By default the CLR is allowed to rearrange (which for simple structs it never does) and pad structs as it pleases. This is typically to keep it aligned to word boundaries when in memory.

If you don't like this behavior and want to change it, you can specify no packing as follows:

[StructLayout(LayoutKind.Sequential,Pack=1)]
like image 160
Guvante Avatar answered Jan 29 '26 01:01

Guvante


Your Identifier struct is padded with 3 bytes when copied to unmanaged memory for alignment reasons.

like image 34
dtb Avatar answered Jan 29 '26 01:01

dtb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!