转换C ++结构,以C#(Convert C++ struct to C#)

2019-06-25 01:22发布

我有以下C ++结构:

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

我怎样才能将其转换为C#结构,序列化,并通过TCP套接字发送?

谢谢!

UPD

因此,C#代码会是什么?

[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);
}

Answer 1:

这个结构的C#版本是:

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

至于通过套接字发送这一点,你可以直接发送二进制数据。 该Marshal类具有用于获得从结构和复制指针(IntPtr的)到一个字节阵列的方法。



Answer 2:

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

编辑:THX芦苇



文章来源: Convert C++ struct to C#
标签: c# c++ struct