CSDN专家博客精华版

为人民服务!
  首页  :: 新随笔  :: 管理

[C#]如何将自定义的structure转换为byte[]?

Posted on 2007-12-17 10:48  csdnexpert  阅读(236)  评论(0)    收藏  举报

如何将自定义的structure转换为byte[]

整理者:郑昀@UltraPower
示例如下:
using System.Runtime.InteropServices;

        public static byte[] RawSerialize( object anything )

        {

            int rawsize = Marshal.SizeOf( anything );

            IntPtr buffer = Marshal.AllocHGlobal( rawsize );

            Marshal.StructureToPtr( anything, buffer, false );

            byte[] rawdatas = new byte[ rawsize ];

            Marshal.Copy( buffer, rawdatas, 0, rawsize );

            Marshal.FreeHGlobal( buffer );

            return rawdatas;

        }

 

        public static object RawDeserialize( byte[] rawdatas, Type anytype )

        {

            int rawsize = Marshal.SizeOf( anytype );

            if( rawsize > rawdatas.Length )

                return null;

            IntPtr buffer = Marshal.AllocHGlobal( rawsize );

            Marshal.Copy( rawdatas, 0, buffer, rawsize );

            object retobj = Marshal.PtrToStructure( buffer, anytype );

            Marshal.FreeHGlobal( buffer );

            return retobj;

                 }

 

        // sample usage:

        [StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]

            struct YourStruct

        {

            public Int32  First;

            public Int32  Second;

            [MarshalAs( UnmanagedType.ByValTStr, SizeConst=16 )]

            public String Text;

        }

 

        YourStruct st;

        st.First  = 11;

        st.Second = 22;

        st.Text = "Hello";

        byte[] rd = RawSerialize( st );

        // reverse:

        YourStruct rst = (YourStruct) RawDeserialize( rd, typeof(YourStruct));

整理者:郑昀@UltraPower



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=340266