我有以下C++結構:轉換C++結構,以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);
}
謝謝您的回答,你能幫助我,是一切ok與我有關複製到緩衝區並把它發送代碼? – Becker
@Becker您應該使用StructureToPtr,而不是GetComInterfaceForObject。請參閱:http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.structuretoptr.aspx#Y1000 –
謝謝!對不起,我從來沒有做過這樣的事情。我編輯了我的代碼,現在都可以嗎? – Becker