macropas
macropas

Reputation: 3160

How to transform one C# structure to another like in C++?

Assume that we have two C# structures:

    [Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct ByteStructure 
    {
        public byte byte0;
        public byte byte1;
        public byte byte2;
        public byte byte3;
        public byte byte4;
        public byte byte5;
        public byte byte6;
        public byte byte7;
        public byte byte8;
        public byte byte9;
        public byte byteA;
        public byte byteB;
        public byte byteC;
        public byte byteD;
        public byte byteE;
        public byte byteF;
     }

     [Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)]
     public struct IntStructure
     {
        public int i0;
        public int i1;
        public int i2;
        public int i3;
      }

      ByteStructure bs;
      IntStructure is;
...

How to transform one structure to another like in C++:

is = (IntStructure)bs;

or

bs = (ByteStructure)is;

Upvotes: 1

Views: 73

Answers (1)

joncham
joncham

Reputation: 1614

The easiest way would be to use the Marshal class and unmanaged memory.

    static void Main(string[] args)
    {
        ByteStructure b = new ByteStructure();
        IntStructure i = new IntStructure();
        i.i0 = 0xa;
        i.i1 = 0xb;
        i.i2 = 0xc;
        i.i3 = 0xd;

        Debug.Assert(Marshal.SizeOf(typeof(IntStructure)) == Marshal.SizeOf(typeof(ByteStructure)));

        IntPtr mem = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntStructure)));
        Marshal.StructureToPtr(i, mem, false);
        b = (ByteStructure)Marshal.PtrToStructure(mem, typeof(ByteStructure));
        Marshal.FreeHGlobal(mem);

    }

Upvotes: 3

Related Questions