using System.Runtime.InteropServices;

        static 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); 
            } 
        }


        unsafe static byte[] Struct2Bytes(object obj)
        {
            int size = Marshal.SizeOf(obj);
            byte[] bytes = new byte[size];
            fixed (byte* pb = &bytes[0])
            {
                Marshal.StructureToPtr(obj, new IntPtr(pb), true);
            }
            return bytes;
        }   
posted on 2011-09-09 17:10  王建全  阅读(433)  评论(3)    收藏  举报