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

}
相關文章
相關標籤/搜索