Convert C ++ struct to C #

I have a C ++ structure 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?

Thank!

update

So, will C # code 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);
}
+5
source share
2 answers

The C # version of this structure will be:

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

As for sending this through a socket, you can just send binary data directly. the marshal's class has methods for getting a pointer (IntPtr) from a structure and copying it into an array of bytes.

+9
source
[StructLayout(LayoutKind.Sequential)]
struct CUSTOM_DATA {
   int id;
   ushort port;
   uint ip;
};
CUSTOM_DATA cData ; // use me 

edit: thanks reed

+1
source

All Articles