c#结构体和字节流之间的相互转换

结构体转byte数组

1  首先要明白 ,是 在那个命名空间下  System.Runtime.InteropServices;

2  首先得到结构体的大小

2  开辟相应的内存空间

3  将结构体填充进开辟的内存空间

4  从内存空间拷贝进byte数组

5  不要忘记释放内存哦

  public static byte[] StructToBytes(object structObj, int size = 0)
    {
        if (size == 0)
        {
            size = Marshal.SizeOf(structObj); //得到结构体大小
        }
        IntPtr buffer = Marshal.AllocHGlobal(size);  //开辟内存空间
        try
        {
            Marshal.StructureToPtr(structObj, buffer, false);   //填充内存空间
            byte[] bytes = new byte[size];
            Marshal.Copy(buffer, bytes, 0, size);   //填充数组
            return bytes;
        }
        catch (Exception ex)
        {
            Debug.LogError("struct to bytes error:" + ex);
            return null;
        }
        finally
        {
            Marshal.FreeHGlobal(buffer);   //释放内存
        }
    }

 

同理,接受到的byte数组,转换为结构体

1  开辟内存空间

2  用数组填充内存空间

3  将内存空间的内容转换为结构体

4 同样不要忘记释放内存

 public static object BytesToStruct(byte[] bytes, Type strcutType, int nSize)
    {
        if (bytes == null)
        {
            Debug.LogError("null bytes!!!!!!!!!!!!!");
        }
        int size = Marshal.SizeOf(strcutType);
        IntPtr buffer = Marshal.AllocHGlobal(nSize);
        //Debug.LogError("Type: " + strcutType.ToString() + "---TypeSize:" + size + "----packetSize:" + nSize);
        try
        {
            Marshal.Copy(bytes, 0, buffer, nSize);
            return Marshal.PtrToStructure(buffer, strcutType);
        }
        catch (Exception ex)
        {
            Debug.LogError("Type: " + strcutType.ToString() + "---TypeSize:" + size + "----packetSize:" + nSize);
            return null;
        }
        finally
        {
            Marshal.FreeHGlobal(buffer);
        }
    }

 

转载于:https://www.cnblogs.com/lzy575566/p/7718815.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值