C++代码如下
typedef struct _ST_CMD_PACKET_ { WORD m_wPrefix; BYTE m_bySrcDeviceID; BYTE m_byDstDeviceID; WORD m_wCMDCode; WORD m_wDataLen; BYTE m_abyData[16]; WORD m_wCheckSum; } ST_CMD_PACKET, *PST_CMD_PACKET; typedef struct _ST_RCM_PACKET_ { WORD m_wPrefix; BYTE m_bySrcDeviceID; BYTE m_byDstDeviceID; WORD m_wCMDCode; WORD m_wDataLen; WORD m_wRetCode; BYTE m_abyData[14]; WORD m_wCheckSum; } ST_RCM_PACKET, *PST_RCM_PACKET; BYTE g_Packet[1024*64]; PST_CMD_PACKET g_pCmdPacket = (PST_CMD_PACKET)g_Packet; PST_RCM_PACKET g_pRcmPacket = (PST_RCM_PACKET)g_Packet; memset( g_Packet, 0, sizeof( g_Packet ));
这段代码转为C#该怎么写,讨教
解决方案
40
结构是指针类型的,你声明的变量其实就是存的结构的引用
10
你可以顺序写入/读出。
例如:
头两个字节为m_wPrefix;
第三个字节为m_bySrcDeviceID;
…
50
结构与字节数组的互换
class Converter { //Structure转为Byte数组,实现了序列化 public static Byte[] StructToBytes(Object structure) { Int32 size = Marshal.SizeOf(structure); //Console.WriteLine(size); IntPtr buffer = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structure, buffer, false); Byte[] bytes = new Byte[size]; Marshal.Copy(buffer, bytes, 0, size); return bytes; } finally { Marshal.FreeHGlobal(buffer); } } //Byte数组转为Structure,实现了反序列化 public static Object BytesToStruct(Byte[] bytes, Type strcutType) { Int32 size = Marshal.SizeOf(strcutType); IntPtr buffer = Marshal.AllocHGlobal(size); try { Marshal.Copy(bytes, 0, buffer, size); return Marshal.PtrToStructure(buffer, strcutType); } finally { Marshal.FreeHGlobal(buffer); } } }