为了账号安全,请及时绑定邮箱和手机立即绑定

如何在C#中将结构转换为字节数组?

如何在C#中将结构转换为字节数组?

C#
慕码人2483693 2019-12-18 13:12:43
如何在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贡献1811条经验 获得超5个赞

如果您真的希望它是快速的,您可以使用不安全的代码与CopyMemory。CopyMemory大约快5倍(例如,800 MB的数据通过编组复制需要3s,而通过CopyMemory复制只需要0.6 s)。此方法限制您只使用实际存储在structblob本身中的数据,例如数字或固定长度字节数组。

    [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;
    }



查看完整回答
反对 回复 2019-12-19
?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

看看这些方法:

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);}

这是一个无耻的副本,另一个线程,我发现谷歌!

更新*有关详细信息,请参阅来源



查看完整回答
反对 回复 2019-12-19
  • 3 回答
  • 0 关注
  • 360 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信