Rosentti
Rosentti
CC#
Created by Rosentti on 9/14/2024 in #help
Strange Marshalling issue
Hi, I'm hitting a strange issue. My Handle_t type, which simply contains an Int32 is the same length as an Int32, as expected. However when it's included in another struct and it's size is checked, the size is incorrect. See below code sample:
c#
using System;
using System.Text;
using System.Runtime.InteropServices;

public class Program
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Handle_t
{
public Int32 m_value;
}

[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct Test_t
{
public Handle_t Test;

[MarshalAs(UnmanagedType.I1)]
public bool Test2;

[MarshalAs(UnmanagedType.I1)]
public bool Test3;
}

[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct TestInt_t
{
public Int32 Test;

[MarshalAs(UnmanagedType.I1)]
public bool Test2;

[MarshalAs(UnmanagedType.I1)]
public bool Test3;
}

public static void Main()
{
Console.WriteLine(Marshal.SizeOf<Int32>()); // 4, OK
Console.WriteLine(Marshal.SizeOf<Handle_t>()); // 4, OK
Console.WriteLine(Marshal.SizeOf<Test_t>()); // 6, not OK, why? It should be 8, as Handle_t only contains an Int32, and is 4 bytes
Console.WriteLine(Marshal.SizeOf<TestInt_t>()); // 8, as expected.
}
}
c#
using System;
using System.Text;
using System.Runtime.InteropServices;

public class Program
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Handle_t
{
public Int32 m_value;
}

[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct Test_t
{
public Handle_t Test;

[MarshalAs(UnmanagedType.I1)]
public bool Test2;

[MarshalAs(UnmanagedType.I1)]
public bool Test3;
}

[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct TestInt_t
{
public Int32 Test;

[MarshalAs(UnmanagedType.I1)]
public bool Test2;

[MarshalAs(UnmanagedType.I1)]
public bool Test3;
}

public static void Main()
{
Console.WriteLine(Marshal.SizeOf<Int32>()); // 4, OK
Console.WriteLine(Marshal.SizeOf<Handle_t>()); // 4, OK
Console.WriteLine(Marshal.SizeOf<Test_t>()); // 6, not OK, why? It should be 8, as Handle_t only contains an Int32, and is 4 bytes
Console.WriteLine(Marshal.SizeOf<TestInt_t>()); // 8, as expected.
}
}
7 replies