简体   繁体   中英

Marshal C# struct into a byte[]

Is there a way to serialize a C# structure, annotated with [StructLayout] , into a managed byte array, ie a byte[] , either premade or with allocation?

I can see marshaling to unmanaged memory then copying, but that's ugly.

Checkout MemoryMarshal.Cast<TFrom, TTo>() . It will easily allow you to change from byte/short/int/long arrays to Structures and back.

https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal?view=netcore-3.1

From my experiences mixing managed and unmanaged data is all about clearly defining the transition from one space to another.

When i have had the requirement of going from native to managed or the other way the first step has always been to copy data to the 'target' space and then forward that.

I assume that you are already familiar with the interop services since you mentioned copying and [StructLayout] .

https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.ptrtostructure?view=netcore-3.1#System_Runtime_InteropServices_Marshal_PtrToStructure_System_IntPtr_System_Object _

If you find a better way please do tell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM