從字節(jié)數(shù)組中讀取C/C 數(shù)據(jù)結(jié)構(gòu)到C#
問題
此任務(wù)涉及將包含來自C/C 結(jié)構(gòu)體數(shù)據(jù)的字節(jié)數(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; }
提出的解決方案
最初,考慮了一種比較繁瑣的方法,涉及固定內(nèi)存并使用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ū)復(fù)制是不必要的。相反,直接的句柄固定就足夠了:
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
類解析數(shù)據(jù)可能會(huì)提供性能優(yōu)勢。但是,必須評估具體的實(shí)現(xiàn)以確定此類增益是否顯著。
以上是如何高效地將 C/C 字節(jié)數(shù)組轉(zhuǎn)換為 C# 結(jié)構(gòu)?的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣服圖片

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

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Stock Market GPT
人工智能驅(qū)動(dòng)投資研究,做出更明智的決策

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的代碼編輯器

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方法實(shí)現(xiàn)內(nèi)存操作日志記錄;2.分配器需定義value_type和rebind模板,以滿足STL容器類型轉(zhuǎn)換需求;3.分配器構(gòu)造與拷貝時(shí)觸發(fā)日志輸出,便于追蹤生命周期;4.實(shí)際應(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)建項(xiàng)目目錄結(jié)構(gòu),包含CMakeLists.txt、src/和include/;2.編寫CMakeLists.txt,指定CMake版本、項(xiàng)目名稱、C 標(biāo)準(zhǔn)并添加可執(zhí)行文件;3.使用mkdirbuild進(jìn)入目錄并運(yùn)行cmake..和cmake--build.進(jìn)行編譯;4.通過add_executable添加多個(gè)源文件,用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,然后實(shí)現(xiàn)解引用、遞增及比較操作,最后在容器中提供begin()和end()方法以返回迭代器實(shí)例,使其兼容STL算法和范圍for循環(huán)。

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