interop - What is the size of the Boolean value in C? Do you really need 4 bytes?

I have two structs with arrays of bytes and booleans:

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct struct1
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
    public byte[] values;
}

[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct struct2
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
    public bool[] values;
}

And the following code:

class main
{
    public static void Main()
    {
        Console.WriteLine("sizeof array of bytes: "+Marshal.SizeOf(typeof(struct1)));
        Console.WriteLine("sizeof array of bools: " + Marshal.SizeOf(typeof(struct2)));
        Console.ReadKey();
    }
}

That gives me the following output:

sizeof array of bytes: 3
sizeof array of bools: 12

It seems to be that a boolean takes 4 bytes of storage. Ideally a boolean would only take one bit (false or true, 0 or 1, etc..).

What is happening here? Is the boolean type really so inefficient?

This question and all comments follow the "Attribution Required."

All Answers

Answers Loading...
Leave a Reply
You must be logged in to post a answer.