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

2022-01-13 03:14:46 字數 2433 閱讀 6768

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的傳送和接收。

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

在c 中的結構體不能定義指標,不能定義字元陣列,只能在裡面定義字元陣列的引用。c 的訊息結構體如下 訊息格式 4 16 4 4 28個位元組 struct cs message c 定義的結構體如下 structlayout layoutkind.sequential,pack 1 public s...

C 中 結 構 體 與 字 節 流 互 相 轉 換

一 c 結構體 1 定義與c 對應的c 結構體 在c 中的結構體不能定義指標,不能定義字元陣列,只能在裡面定義字元陣列的引用。c 的訊息結構體如下 訊息格式 4 16 4 4 28個位元組 struct cs message c 定義的結構體如下 structlayout layoutkind.se...

c 位元組流與結構體互轉

c 是型別不安全的,一般位元組流和結構體是可以互相強轉的,但前提是位元組流要像結構體一樣進行資料對齊,下面就來看看按資料大小依次排列的位元組流是如何轉化為結構體的 基礎依賴部分 include include include namespace sangame tdata8 typedef unio...