C# 字节转结构体、结构体转字节

/// <summary>  
/// 结构体转bytes  
/// </summary>  
/// <param name="structObj">结构体</param>  
/// <param name="decCount">默认0,不截取</param>  
/// <returns></returns>  
public static byte[] StructToBytes(object structObj, Int32 decCount)
{
    Int32 size = Marshal.SizeOf(structObj);
    //开辟空间  
    IntPtr buffer = Marshal.AllocHGlobal(size);
    try
    {
        Marshal.StructureToPtr(structObj, buffer, false);
        byte[] bytes = new byte[size - decCount];
        Marshal.Copy(buffer, bytes, 0, size - decCount);
        return bytes;
    }
    finally
    {
        //释放空间  
        Marshal.FreeHGlobal(buffer);
    }
}
/// <summary>  
/// byte转结构体  
/// </summary>  
/// <param name="bytes">byte数组</param>  
/// <param name="type">结构体类型</param>  
/// <returns></returns>  
public static object ByteToStruct(byte[] bytes, Type type)
{
    Int32 size = Marshal.SizeOf(type);
    //byte数组长度小于结构体大小  
    if (size > bytes.Length)
    {
        //返回空  
        return null;
    }
    //分配结构大小的内存空间  
    IntPtr structPtr = Marshal.AllocHGlobal(size);
    //将byte数组拷贝到分配好的内存空间  
    Marshal.Copy(bytes, 0, structPtr, size);
    //将内存空间转换成目标结构  
    object obj = Marshal.PtrToStructure(structPtr, type);
    //释放内存空间  
    Marshal.FreeHGlobal(structPtr);
    //返回结构  
    return obj;
}

 

posted on 2020-11-10 13:05  炼金师  阅读(417)  评论(0编辑  收藏  举报

导航