C#中結構體與位元組流互相轉換

來源:互聯網
上載者:User

標籤:class   get   使用   strong   檔案   string   

1、定義與C++對應的C#結構體

在c#中的結構體不能定義指標,不能定義字元數組,只能在裡面定義字元數組的引用。

C++的訊息結構體如下:

//訊息格式 4+16+4+4= 28個位元組

struct cs_message{

u32_t cmd_type;

char username[16];

u32_t dstID;

u32_t srcID;

};

C#定義的結構體如下:

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

public struct my_message

{

public UInt32 cmd_type;

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

public string username;

public UInt32 dstID;

public UInt32 srcID;

public my_message(string s)

{

cmd_type = 0;

username = s;

dstID = 0;

srcID = 0;

}

}

在C++的標頭檔定義中,使用了 #pragma pack 1 位元組按1對齊,所以C#的結構體也必須要加上對應的特性,LayoutKind.Sequential屬性讓結構體在匯出到非託管記憶體時按出現的順序依次布局,而對於C++的char數群組類型,C#中可以直接使用string來對應,當然了,也要加上封送的特性和長度限制。 2、結構體與byte[]的互相轉換

定義一個類,裡面有2個方法去實現互轉:

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

}

}

} 3、測試結果:

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

}

結構體的size是28個位元組和c++的結構體一樣,同時可以將結構體和位元組數組互轉,方便UDP的發送和接收。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.