0

My aim with this code is to send a struct to a server which waits for this struct to read the data out of it. So i have to serialize all the references in order to give the server a struct which it can read and understand.

I have got a struct which contains long, ulong, string, enum, long[] and other struct. I've already searched on stackoverflow, but all the solutions serialize my struct to zeros except the strings.

How do I serialize the struct properly, then save it to byte[] and finally send it with tcp ?

My Header-Struct (that's why my struct looks like this):

  [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Pack = 4, Size = size)]
            public struct _HEADER 
            {
                [FieldOffset(0)]
                public Constants._TYPE Type;
                [FieldOffset(4)]
                public long Cr;
                [FieldOffset(12)]
                public Id Id;
                [FieldOffset(SIZE+12), MarshalAs(UnmanagedType.ByValArray)]  
                public long[] array;
            }

[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Pack = 4, Size = SIZE)]
            public struct Id
            {
                [FieldOffset(0)]
                public long Protocol;
                [FieldOffset(8)]
                public long Protocol;
                [FieldOffset(16)]
                public Constants._TYPE CType;
                [FieldOffset(20)]
                public Constants._TYPE Cred;
                [FieldOffset(24)]
                public Constants._TYPE CGred;
            }

My CURRENT method to serialize the struct:

    IntPtr pointer = Marshal.AllocHGlobal(Marshal.SizeOf(header));
    Marshal.StructureToPtr(header, pointer, false);
    byte[] headerdata = new byte[Marshal.SizeOf(header)];
    Marshal.Copy(pointer, headerdata, 0, headerdata.Length);
    Marshal.FreeHGlobal(pointer);

My CURRENT method to send the data:

_socket.Send(headerdata);

This is what I get in the tcp-packet, which I send to the server:

Community
  • 1
  • 1
David
  • 273
  • 2
  • 20

1 Answers1

0

Why not to use BinaryFormatter? https://msdn.microsoft.com/en-us/library/c5sbs8z9(v=vs.110).aspx

alexrait
  • 407
  • 3
  • 15