Accessing unmanaged struct

  • Thread starter Thread starter Dev10110110
  • Start date Start date
D

Dev10110110

Guest
In the following code, is there a better way I can change Data.INNER[0] fields? The hard-coding bit is not ideal, and I want to avoid it if possible. Thanks.

static class Program
{
[ StructLayout( LayoutKind.Sequential, Pack = 1 ) ]
struct INNER
{
public UInt16 InnerField1;
public byte InnerField2;
}


[ StructLayout( LayoutKind.Sequential, Pack = 1 ) ]
unsafe struct OUTER
{
public byte OuterField1;
public fixed byte Blob[6]; // holds INNER[2]
}


static void Main ()
{
OUTER Data; // assume this is filled with valid data
Data.OuterField1 = 1;

unsafe
{
byte *p = (byte *) &Data;
p += 1; // hard-coding of Blob/INNER offset

((INNER *) p)->InnerField1 = 2;
((INNER *) p)->InnerField2 = 3;
}
}
}

Continue reading...
 
Back
Top