7

I have a C++ struct below:

struct CUSTOM_DATA {
   int id;
   u_short port;
   unsigned long ip;
} custom_data;

How can i convert it to C# struct, serialize it and send via tcp socket?

Thanks!

upd

So C# code will be?

[StructLayout(LayoutKind.Sequential)]
public struct CustomData
{
 public int id;
 public ushort port;
 public uint ip;
}

public void Send()
{
 CustomData d = new CustomData();
 d.id = 12;
 d.port = 1000;
 d.ip = BitConverter.ToUInt32(IPAddress.Any.GetAddressBytes(), 0);
 IntPtr pointer = Marshal.AllocHGlobal(Marshal.SizeOf(d));
 Marshal.StructureToPtr(d, pointer, false);
 byte[] data_to_send = new byte[Marshal.SizeOf(d)];
 Marshal.Copy(pointer, data_to_send, 0, data_to_send.Length);
 client.GetStream().Write(data_to_send, 0, data_to_send.Length);
}
Becker
  • 175
  • 2
  • 3
  • 11

2 Answers2

11

The C# version of this struct would be:

[StructLayout(LayoutKind.Sequential)]
public struct CustomData
{
    public int id;
    public ushort port;
    public uint ip;
}

As for sending this via a socket, you can just send the binary data directly. The Marshal class has methods for getting a pointer (IntPtr) from the structure and copying into a byte array.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Thanks for your answer, can you help me, is all ok with my code about copying to buffer and sending it? – Becker May 31 '12 at 21:02
  • @Becker You should use StructureToPtr, not GetComInterfaceForObject. See: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.structuretoptr.aspx#Y1000 – Reed Copsey May 31 '12 at 21:22
  • Thanks! Sorry, i just never done things like this before. I edited my code, now all ok? – Becker Jun 01 '12 at 10:33
1
[StructLayout(LayoutKind.Sequential)]
struct CUSTOM_DATA {
   int id;
   ushort port;
   uint ip;
};
CUSTOM_DATA cData ; // use me 

edit: thx reed

corn3lius
  • 4,857
  • 2
  • 31
  • 36