problem with constructor of struct using FieldOffset

S

Steve Richter

I have a struct that uses LayoutKind.Explicit to redefine bytes within
the struct:

[StructLayout(LayoutKind.Explicit)]
public struct PointerStoredValue
{
[FieldOffset(0)]
public int LayoutId;
[FieldOffset(4)]
public int HeapId ;
[FieldOffset(8)]
public int BufferBx;
[FieldOffset(12)]
public int EmptySpace;
[FieldOffset(0)]
public long Part1;
[FieldOffset(8)]
public long Part2;

public PointerStoredValue(byte[] InArray, int InBx)
{
Part1 = BitConverter.ToInt64(InArray, InBx);
Part2 = BitConverter.ToInt64(InArray, InBx + 8);
}
}

the constructor will not compile:
"field LayoutId must be fully assigned before control leaves the
constructor"

the Part1 field is a long from bytes 0 to 7 of the struct. field
LayoutId is an int from bytes 0 to 3. By assigning to field Part1,
field LayoutId is being assigned.

Why the compiler error?

thanks,

-Steve
 
J

Jon Skeet [C# MVP]

the constructor will not compile:
"field LayoutId must be fully assigned before control leaves the
constructor"

the Part1 field is a long from bytes 0 to 7 of the struct. field
LayoutId is an int from bytes 0 to 3. By assigning to field Part1,
field LayoutId is being assigned.

Why the compiler error?

The compiler doesn't know about the FieldOffsetAttribute itself. If you
just assign the "duplicate" fields any value (before Part1 and Part2)
you'll get the desired effect.
 
S

Steve Richter

The compiler doesn't know about the FieldOffsetAttribute itself. If you
just assign the "duplicate" fields any value (before Part1 and Part2)
you'll get the desired effect.

thanks for the confirmation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top