我在下面有一个C ++结构:
struct CUSTOM_DATA {
int id;
u_short port;
unsigned long ip;
} custom_data;
如何将其转换为C#struct,序列化并通过tcp socket发送?
谢谢!
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);
}
答案 0 :(得分:11)
此结构的C#版本将是:
[StructLayout(LayoutKind.Sequential)]
public struct CustomData
{
public int id;
public ushort port;
public uint ip;
}
至于通过套接字发送,您可以直接发送二进制数据。 Marshal class具有从结构获取指针(IntPtr)并复制到字节数组的方法。
答案 1 :(得分:1)
[StructLayout(LayoutKind.Sequential)]
struct CUSTOM_DATA {
int id;
ushort port;
uint ip;
};
CUSTOM_DATA cData ; // use me
编辑: thx reed