如何在C#中将结构转换为字节数组?如何在C#中将结构转换为字节数组?我定义了这样一个结构:public struct CIFSPacket{
public uint protocolIdentifier; //The value must be "0xFF+'SMB'".
public byte command;
public byte errorClass;
public byte reserved;
public ushort error;
public byte flags;
//Here there are 14 bytes of data which is used differently among different dialects.
//I do want the flags2. However, so I'll try parsing them.
public ushort flags2;
public ushort treeId;
public ushort processId;
public ushort userId;
public ushort multiplexId;
//Trans request
public byte wordCount;//Count of parameter words defining the data portion of the packet.
//From here it might be undefined...
public int parametersStartIndex;
public ushort byteCount; //Buffer length
public int bufferStartIndex;
public string Buffer;}在我的主要方法中,我创建它的一个实例并给它赋值:CIFSPacket packet = new CIFSPacket();packet.protocolIdentifier = 0xff;packet.command = (byte)CommandTypes.SMB_COM_NEGOTIATE;
packet.errorClass = 0xff;packet.error = 0;packet.flags = 0x00;packet.flags2 = 0x0001;packet.multiplexId = 22;packet.wordCount = 0;
packet.byteCount = 119;packet.Buffer = "NT LM 0.12";现在我想用套接字发送这个包。为此,我需要将结构转换为字节数组。我该怎么做?代码片段是什么?
3 回答
冉冉说
TA贡献1877条经验 获得超1个赞
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)] private static unsafe extern void CopyMemory(void *dest, void *src, int count); private static unsafe byte[] Serialize(TestStruct[] index) { var buffer = new byte[Marshal.SizeOf(typeof(TestStruct)) * index.Length]; fixed (void* d = &buffer[0]) { fixed (void* s = &index[0]) { CopyMemory(d, s, buffer.Length); } } return buffer; }
潇湘沐
TA贡献1816条经验 获得超6个赞
byte [] StructureToByteArray(object obj){ int len = Marshal.SizeOf(obj); byte [] arr = new byte[len]; IntPtr ptr = Marshal.AllocHGlobal(len); Marshal.StructureToPtr(obj, ptr, true); Marshal.Copy(ptr, arr, 0, len); Marshal.FreeHGlobal(ptr); return arr;}void ByteArrayToStructure(byte [] bytearray, ref object obj){ int len = Marshal.SizeOf(obj); IntPtr i = Marshal.AllocHGlobal(len); Marshal.Copy(bytearray,0, i,len); obj = Marshal.PtrToStructure(i, obj.GetType()); Marshal.FreeHGlobal(i);}
更新
- 3 回答
- 0 关注
- 335 浏览
添加回答
举报
0/150
提交
取消