1. 程式人生 > >C#中結構體與位元組流互相轉換

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

}