结构体和二进制转换

来源:互联网 发布:唯一网络王宇杰老婆 编辑:程序博客网 时间:2024/06/07 11:05


记录:

using UnityEngine;
using System.IO;using System.Runtime.InteropServices;/// <summary>/// 结构体和二进制相互转换/// </summary>public class FileTest11 : MonoBehaviour {    private int size;// Use this for initializationvoid Start () {        FileStream fs = new FileStream("d://jtest11.txt", FileMode.OpenOrCreate);        BinaryWriter b = new BinaryWriter(fs);        Vector3 v = new Vector3(31, 2, 3);        byte[] bytes = StructToBytes(v);        b.Write(StructToBytes(v));        b.Close();        for (int i = 0; i < bytes.Length; i++) {            Debug.LogError("============="+bytes[i]);        }        //b.    }// Update is called once per framevoid Update () {        if (Input.GetKeyDown(KeyCode.Space)) {            FileStream fstream= File.OpenRead("d://jtest11.txt");            BinaryReader reader = new BinaryReader(fstream);            byte[] bs= reader.ReadBytes(size);            Debug.LogError("================" + (Vector3)BytesToStruct(bs, typeof(Vector3)));            reader.Close();        }}    public byte[] StructToBytes(object obj)    {        //得到结构体的大小         size = Marshal.SizeOf(obj);        //创建byte数组        byte[] bytes = new byte[size];        //分配结构体大小的内存空间        System.IntPtr structPtr = Marshal.AllocHGlobal(size);        //将结构体拷到分配好的内存空间        Marshal.StructureToPtr(obj, structPtr, false);        //从内存空间拷到byte数组        Marshal.Copy(structPtr, bytes, 0, size);        //释放内存空间        Marshal.FreeHGlobal(structPtr);        //返回byte数组        return bytes;    }    /// <summary>    /// byte数组转结构    /// </summary>    /// <param name="bytes">byte数组</param>    /// <param name="type">结构类型</param>    /// <returns>转换后的结构</returns>    public object BytesToStruct(byte[] bytes, System.Type type)    {        //得到结构的大小        int size = Marshal.SizeOf(type);        Debug.LogError(size.ToString());        //byte数组长度小于结构的大小        if (size > bytes.Length)        {            //返回空            return null;        }        //分配结构大小的内存空间        System.IntPtr structPtr = Marshal.AllocHGlobal(size);        //将byte数组拷到分配好的内存空间        Marshal.Copy(bytes, 0, structPtr, size);        //将内存空间转换为目标结构        object obj = Marshal.PtrToStructure(structPtr, type);        //释放内存空间        Marshal.FreeHGlobal(structPtr);        //返回结构        return obj;    }}

原创粉丝点击