0

First off, sorry about the vague title, but I couldn't think of a better one.

Basically, I have a struct defined as so:

[StructLayout(LayoutKind.Explicit)]
public struct SinkHead {
    [FieldOffset(0)]
    public long AsLong;

    [FieldOffset(1)]
    public bool UseSink1;

    [FieldOffset(4)]
    public int LastSinkSlot;
}

Later on, I have the following code:

private const long INITIAL_VALUE_SINK1_HEAD = 0x00FF0000FFFFFFFFL;
private SinkHead sinkHead = new SinkHead { AsLong = INITIAL_VALUE_SINK1_HEAD };

Then, I immediately print the following line:

Console.WriteLine(sinkHead.LastSinkSlot);

I would expect to see -1, but instead, I get 16711680 (which is 0x00FF0000).

I thought the field offset of 4 would set the LastSinkSlot value to 0xFFFFFFFF, which is -1 for a signed 32-bit int.

My first thought was that this was some trouble with endianess, but then surely I'd just get it reading 0xFFFFFFFF backwards from the same offset? Or, I would expect to see the value for 0x0000FF00.

Alternatively, maybe FieldOffset doesn't so what I thin, but either way I don't get it.

Incidentally, changing the struct to look like this makes it work just fine:

[StructLayout(LayoutKind.Explicit)]
public struct SinkHead {
    [FieldOffset(0)]
    public long AsLong;

    [FieldOffset(6)]
    public bool UseSink1;

    [FieldOffset(0)]
    public int LastSinkSlot;
}

Which makes me wonder if the long is being swapped in two halves or something... But I don't know.

Xenoprimate
  • 7,691
  • 15
  • 58
  • 95
  • Have you tried specifying also the [`Pack` field](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.pack.aspx) on your `StructLayout` attribute? Haven't tested that myself. – Jeppe Stig Nielsen Apr 01 '14 at 21:41
  • I believe that everything works as expected. What's your question? Does the x86/x64 use little-endian? Yup. – Dmitry Apr 01 '14 at 21:43
  • @Dmitry I would expect an int captured from the fourth byte of long '0x00FF0000FFFFFFFFL' to be '0xFFFFFFFF' - is that wrong? – Xenoprimate Apr 01 '14 at 21:51
  • 2
    It is wrong because of the [little-endian](http://en.wikipedia.org/wiki/Endianness): `As examples, the Intel x86 processor represents a common little-endian architecture` – Dmitry Apr 01 '14 at 21:54

0 Answers0