c 中關於結構體和位元組陣列轉化

2021-07-11 04:32:41 字數 4447 閱讀 7413

最近在使用結構體與位元組陣列轉化來實現socket間資料傳輸。現在開始整理一下。對於marshal可以查閱msdn,關於位元組陣列與結構體轉**如下:

usingsystem;

usingsystem.collections.generic;

usingsystem.linq;

usingsystem.text;

usingsystem.io;

usingsystem.runtime.interopservices;

namespacefilesendclient

unsafeclassprogram

;

sd.e = 5;

intsize = 0;

//此處使用非安全**來獲取到structdemo的值

unsafe

byteb = structtobytes(sd,size);

bytetostruct(b,typeof(structdemo));

}

//將byte轉換為結構體型別

publicstaticbytestructtobytes(objectstructobj,intsize)

//將byte轉換為結構體型別

publicstaticobjectbytetostruct(bytebytes, type type)

//分配結構體記憶體空間

intptr structptr = marshal.allochglobal(size);

//將byte陣列拷貝到分配好的記憶體空間

marshal.copy(bytes, 0, structptr, size);

//將記憶體空間轉換為目標結構體

objectobj = marshal.ptrtostructure(structptr, type);

//釋放記憶體空間

marshal.freehglobal(structptr);

returnobj;

}

}

}

最近在使用結構體與位元組陣列轉化來實現socket間資料傳輸。現在開始整理一下。對於marshal可以查閱msdn,關於位元組陣列與結構體轉**如下:

usingsystem;

usingsystem.collections.generic;

usingsystem.linq;

usingsystem.text;

usingsystem.io;

usingsystem.runtime.interopservices;

namespacefilesendclient

unsafeclassprogram

;

sd.e = 5;

intsize = 0;

//此處使用非安全**來獲取到structdemo的值

unsafe

byteb = structtobytes(sd,size);

bytetostruct(b,typeof(structdemo));

}

//將byte轉換為結構體型別

publicstaticbytestructtobytes(objectstructobj,intsize)

//將byte轉換為結構體型別

publicstaticobjectbytetostruct(bytebytes, type type)

//分配結構體記憶體空間

intptr structptr = marshal.allochglobal(size);

//將byte陣列拷貝到分配好的記憶體空間

marshal.copy(bytes, 0, structptr, size);

//將記憶體空間轉換為目標結構體

objectobj = marshal.ptrtostructure(structptr, type);

//釋放記憶體空間

marshal.freehglobal(structptr);

returnobj;

}

}

}

C 中結構體和位元組陣列轉換實現

using system using system.collections.generic using system.linq using system.text us程式設計客棧ing system.io using system.runtime.interopservices namespace...

C 結構體和位元組陣列的轉換

c 結構體和位元組陣列的轉換 在寫c tcp通訊程式時,傳送資料時,只能傳送byte陣列,處理起來比較麻煩不說,如果是和vc6.0等寫的程式通訊的話,很多的都是傳送結構體,在vc6.0中可以很方便的把乙個char陣列轉換為乙個結構體,而在c 卻不能直接把byte陣列轉換為結構體,要在c 中傳送結構體...

C 結構體和位元組陣列的轉換

本文主要起源於專案從c 轉到c 時碰到的問題,即套接字傳送資訊時的型別轉換。在c 中,套接字傳送和接收的型別為字元陣列char,而char與結構體struct可以直接進行顯式轉換就可以 在c 中,sockets類和networkstream類傳送和接收的型別為位元組陣列byte,而它與結構體的轉換並...