Seva Alekseyev
Seva Alekseyev

Reputation: 61341

Marshal C# struct into a byte[]

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

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

Upvotes: 1

Views: 2241

Answers (2)

Matthew Whited
Matthew Whited

Reputation: 22433

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

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

Upvotes: 3

Ivan Naumovski
Ivan Naumovski

Reputation: 69

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://learn.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

Upvotes: 0

Related Questions