将C++结构体转换为C#

7

我有一个C++结构体如下:

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

我该如何将它转换成C#结构体,序列化并通过TCP套接字发送?

谢谢!

更新

那么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);
}
2个回答

11

这个结构体的C#版本如下:

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

如果要通过套接字发送此数据,您可以直接发送二进制数据。 Marshal类具有从结构体获取指针(IntPtr)并将其复制到字节数组的方法。


谢谢你的回答,你能帮我确认一下关于复制到缓冲区并发送代码的问题吗? - Becker
@Becker,你应该使用StructureToPtr而不是GetComInterfaceForObject。请参考:http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.structuretoptr.aspx#Y1000 - Reed Copsey
谢谢!抱歉,我以前从来没有做过这样的事情。我编辑了我的代码,现在一切都好了吗? - Becker

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

编辑:谢谢 Reed


3
应该使用uint,而不是ulong - C++中的“unsigned long”是4个字节,即C#中的UInt32。 - Reed Copsey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接