從位元組數(shù)組讀取C/C 資料結(jié)構(gòu)到C#
問題
此任務(wù)涉及將包含來自C/C 結(jié)構(gòu)體資料的位元組數(shù)組轉(zhuǎn)換為對應(yīng)的C#結(jié)構(gòu)體。 C/C 結(jié)構(gòu)體如下圖所示:
typedef struct OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12]; } OldStuff;
而C#結(jié)構(gòu)體,名為NewStuff
,定義如下:
[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking; }
提出的解決方案
最初,考慮了一種比較繁瑣的方法,涉及固定記憶體並使用Marshal.PtrToStructure
:
int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize]; Array.Copy(SomeByteArray, 0, buff, 0, BufferSize); handle = GCHandle.Alloc(buff, GCHandleType.Pinned); MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); handle.Free();
改進(jìn)
經(jīng)過進(jìn)一步分析,確定原始方法中的緩衝區(qū)複製是不必要的。相反,直接的句柄固定就夠了:
GCHandle handle; NewStuff MyStuff; handle = GCHandle.Alloc(SomeByteArray, GCHandleType.Pinned); try { MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); } finally { handle.Free(); }
此外,可以使用泛型甚至更簡單的版本(需要不安全切換):
- 泛型:
T ByteArrayToStructure<T>(byte[] bytes) where T : struct { T stuff; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } return stuff; }
- 更簡單(不安全):
unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct { fixed (byte* ptr = &bytes[0]) { return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T)); } }
使用BinaryReader提高效能
雖然首選的解決方案涉及固定和Marshal.PtrToStructure
,但在特定情況下,使用BinaryReader
類別解析資料可能會提供效能優(yōu)勢。但是,必須評估具體的實現(xiàn)以確定此類增益是否顯著。
以上是如何有效率地將 C/C 位元組數(shù)組轉(zhuǎn)換為 C# 結(jié)構(gòu)?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT
人工智慧支援投資研究,做出更明智的決策

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

InstallaC compilerlikeg usingpackagemanagersordevelopmenttoolsdependingontheOS.2.WriteaC programandsaveitwitha.cppextension.3.Compiletheprogramusingg hello.cpp-ohellotogenerateanexecutable.4.Runtheexecutablewith./helloonLinux/macOSorhello.exeonWi

自定義分配器可用於控制C 容器的內(nèi)存分配行為,1.示例中的LoggingAllocator通過重載allocate、deallocate、construct和destroy方法實現(xiàn)內(nèi)存操作日誌記錄;2.分配器需定義value_type和rebind模板,以滿足STL容器類型轉(zhuǎn)換需求;3.分配器構(gòu)造與拷貝時觸發(fā)日誌輸出,便於追蹤生命週期;4.實際應(yīng)用包括內(nèi)存池、共享內(nèi)存、調(diào)試工具和嵌入式系統(tǒng);5.C 17起construct和destroy可由std::allocator_traits默認(rèn)處理

使用std::system()函數(shù)可執(zhí)行系統(tǒng)命令,需包含頭文件,傳入C風(fēng)格字符串命令,如std::system("ls-l"),返回值為-1表示命令處理器不可用。

創(chuàng)建項目目錄結(jié)構(gòu),包含CMakeLists.txt、src/和include/;2.編寫CMakeLists.txt,指定CMake版本、項目名稱、C 標(biāo)準(zhǔn)並添加可執(zhí)行文件;3.使用mkdirbuild進(jìn)入目錄並運行cmake..和cmake--build.進(jìn)行編譯;4.通過add_executable添加多個源文件,用target_include_directories包含頭文件路徑;5.使用find_package查找外部庫並用target_link_libraries鏈接;6.通過tar

C 的stack是STL中的容器適配器,遵循後進(jìn)先出原則,需包含頭文件;通過push添加元素,pop移除頂部元素,top訪問棧頂,操作前應(yīng)檢查是否為空,常用於表達(dá)式求值、回溯等場景。

Theautokeywordletsthecompilerdeducevariabletypesfrominitializers,reducingverbosityandimprovingmaintainability.Itsimplifiescodewithcomplextypeslikeiteratorsandlambdas,supportsreferencesandconstqualifierstoavoidunnecessarycopies,andadaptsautomaticallyw

答案是定義包含必要類型別名和操作的類。首先設(shè)置value_type、reference、pointer、difference_type和iterator_category,然後實現(xiàn)解引用、遞增及比較操作,最後在容器中提供begin()和end()方法以返回迭代器實例,使其兼容STL算法和範(fàn)圍for循環(huán)。

AstaticVariableInc witherinsitvaluebetwunctioncallsandisinitializedonce.2.Inideafunction,itpreservesstataTateAcrossCalls,siseascountingIterations.3.inaclass,itissharedamondamongallinStancessandMustancessandMustancessandMustbedIendEctIndEtheClastoAvoVovoiDlinkingErrors.4.StaticvariA.StaticvAriA.StaticVariA.StaticVariA
