【代码块】-结构体序列化与反序列化

整理代码块

代码块整理后存储,供后期使用

结构体序列化与反序列化

using System;
using System.Runtime.InteropServices;
using System.Text;

namespace structTest
{
    /// <summary>
    /// 结构体序列化
    /// </summary>
    public class structSerializable
    {
        //Structure转为byte数组,实现了序列化 
        public byte[] StructToBytes(object structure)
        {
            int size = Marshal.SizeOf(structure);
            //unsafe
            //{
            // size = sizeof(new MyStruct);
            //}
            //Console.WriteLine(size);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(structure, buffer, false);
                byte[] bytes = new byte[size];
                Marshal.Copy(buffer, bytes, 0, size);
                return bytes;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        //byte数组转为Structure,实现了反序列化 
        public object BytesToStruct(byte[] bytes, Type strcutType)
        {
            int size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(bytes, 0, buffer, size);
                return Marshal.PtrToStructure(buffer, strcutType);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        public struct MyStruct
        {
            public byte[] _int;
            public byte[] _long;
            public byte[] _byte;
            //public float _float;
        }
        public void strcut()
        {
            byte[] Mybate = Encoding.ASCII.GetBytes("xiaLuoTest1234567890");
            byte[] Mybate1 = Encoding.ASCII.GetBytes("zhangsan");
            byte[] Mybate2 = Encoding.ASCII.GetBytes("lisi");

            MyStruct ms = new MyStruct();// size:24
            ms._int = Mybate;
            ms._long = Mybate1;
            ms._byte = Mybate2;
            //ms._float = 1.2f;

            //object getRtn = BytesToStruct(Mybate, ms.GetType());
            byte[] getbyte = StructToBytes(ms);

            //Console.WriteLine("define : _float:{0} _int:{1} \r\n", ms._int, ms._long = 123456);
            //Console.WriteLine("BytesToStruct: \r\n_float:{0} _int:{1} ", ((MyStruct)getRtn)._int, ((MyStruct)getRtn)._long);
            int i = 0;
            foreach (byte item in getbyte)
            {
                Console.WriteLine(i + " : " + item);
                i++;
            }
            Console.ReadKey();
        }
    }
}
posted @ 2023-12-20 21:44  叫夏洛啊  阅读(3)  评论(0编辑  收藏  举报