Quiz: what does the following program print?
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication2 {
[StructLayout(LayoutKind.Sequential, Pack=1)]
struct Struct1 {
bool b;
int i;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
struct Struct2 {
byte b;
int i;
}
class Program {
static void Main(string[] args) {
Console.WriteLine(Marshal.SizeOf(typeof(Struct1)));
Console.WriteLine(Marshal.SizeOf(typeof(Struct2)));
Console.ReadKey();
}
}
}
Answer:
8
5
This is very confusing to me. Both bool and byte have a size of 1 byte, and specifying [StructLayout(LayoutKind.Sequential, Pack=1)]
should nullify any padding issues. Both structs should be 5 bytes. So I have two questions:
Thanks.
By default, .NET type bool
marshals to unmanaged type BOOL
, which is typedef
ed to int
. If you want to marshal to and from 1-byte unmanaged booleans, indicate this to the marshaler with an attribute:
[StructLayout (LayoutKind.Sequential, Pack=1)]
struct Struct3 {
[MarshalAs (UnmanagedType.I1)]
bool b;
int i;
}
Console.WriteLine (Marshal.SizeOf (typeof (Struct3))) ; // prints 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With