• C#结构体和字节数组的相互转化(转)


    public static class StructCopyer
    {
        //相当于序列化与反序列化,但是不用借助外部文件
        
    //1、struct转换为Byte[]
        public static Byte[] StructToBytes(Object structure)
        {
            Int32 size = Marshal.SizeOf(structure);
            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);
            }

        }

        //2、Byte[]转换为struct
        public static Object BytesToStruct(Byte[] bytes, Type strcutType)
        {
            Int32 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);
            }
        }

    }

    用法:

    //InterfaceStruct为一结构体
    InterfaceStruct pInterface = new InterfaceStruct();

    pInterface = (InterfaceStruct)BytesToStruct(bytPipeInfo, pInterface.GetType());  


    转自:http://www.cnblogs.com/jingmoxukong/articles/2118105.html

  • 相关阅读:
    MySQL实现了四种通信协议
    深入了解Windows句柄到底是什么
    Linux虚拟地址空间布局以及进程栈和线程栈总结
    malloc 函数详解
    数组指针和指针数组的区别
    Linux中sudo配置
    ctrl+c,ctrl+d,ctrl+z在linux程序中意义和区别
    linux select函数详解
    linux grep命令详解
    Linux find 用法示例
  • 原文地址:https://www.cnblogs.com/zhangpengshou/p/2196474.html
Copyright © 2020-2023  润新知