1

Trying to call DeviceIoControl function from managed code. Have couple structures defined like this:

[StructLayout(LayoutKind.Explicit)]
public struct PARTITION_INFORMATION_UNION
{
    [FieldOffset(0)]
    public PARTITION_INFORMATION_MBR Mbr;
    [FieldOffset(0)]
    public PARTITION_INFORMATION_GPT Gpt;
}

[StructLayout(LayoutKind.Sequential)]
public struct PARTITION_INFORMATION_MBR
{
    public byte PartitionType;
    public bool BootIndicator;
    public bool RecognizedPartition;
    public UInt32 HiddenSectors;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct PARTITION_INFORMATION_GPT
{
    public Guid PartitionType;
    public Guid PartitionId;
    [MarshalAs(UnmanagedType.U8)]
    public UInt64 Attributes;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)]
    public String Name;
}

Works fine if I build my application in x86, but fails during run-time if built for x64 with the following error message:

Unhandled Exception: System.TypeLoadException: Could not load type PARTITION_INFORMATION_UNION' from assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.

Any idea what am I doing wrong?

Update: as far as I understand problem is with last string defined in PARTITION_INFORMATION_GPT. If I replace it with 9 8-byte numbers, or simple comment out and put hardcoded Size into structure attributes - everything works fine.

sha
  • 17,824
  • 5
  • 63
  • 98
  • This looks like an x64 jitter bug to me, there is no overlap. You can report it at connect.microsoft.com. A workaround is `fixed char Name[36]`, unsafe keyword required. – Hans Passant Jan 02 '13 at 19:54
  • That's an easiest answer :) But I'm not ready to blame Microsoft for that... – sha Jan 03 '13 at 00:30
  • 1
    I just ran into this myself. If you put field offset attributes on the PARTITION_INFORMATION_GPT fields and change it to explicit layout, it works. I found the solution in this question http://stackoverflow.com/questions/35786764/creating-multiple-partitions-on-usb-using-c-sharp/35792276 – J.H. Nov 01 '16 at 21:32
  • @J.H. - thank you so much for that reference!!! it just saved me. – Tar Mar 02 '17 at 22:53

0 Answers0