C#中结构体与字节流互相转换

C++的消息结构体如下

struct cs_message{

         u32_t        cmd_type;

         char username[16];

         u32_t        dstID;

         u32_t        srcID;

};
public class Converter
{
        public Byte[] StructToBytes(Object structure)
        {
            Int32 size = Marshal.SizeOf(structure);
            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);
            }
        }

        public 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);
            }
        }
}
static void Main(string[] args)

{

    //定义转换类的一个对象并初始化

Converter Convert = new Converter();

//定义消息结构体

    my_message m;

 

    //初始化消息结构体

    m = new my_message("yanlina");

    m.cmd_type = 1633837924;

    m.srcID = 1633837924;

m.dstID = 1633837924;

 

//使用转换类的对象的StructToBytes方法把m结构体转换成Byte

Byte[] message = Convert.StructToBytes(m);

//使用转换类的对象的BytesToStruct方法把Byte转换成m结构体

my_message n = (my_message)Convert.BytesToStruct(message, m.GetType());

//输出测试

    Console.WriteLine(Encoding.ASCII.GetString(message));

    Console.WriteLine(n.username);

}

猜你喜欢

转载自www.cnblogs.com/ChangTan/p/9950371.html
今日推荐