将 C# 结构编组为 byte[]

Marshal C# struct into a byte[]

有没有办法将用 [StructLayout] 注释的 C# 结构序列化为 managed 字节数组,我。 e. a byte[],是预制的还是分配的?

我可以看到编组到非托管内存然后复制,但这很丑陋。

根据我的经验,混合托管和非托管数据就是要明确定义从一个 space 到另一个的过渡。

当我有从本机到托管或其他方式的要求时,第一步始终是将数据复制到 'target' space 然后转发。

我假设您已经熟悉了互操作服务,因为您提到了复制和 [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_

如果你找到更好的方法请告诉

结帐MemoryMarshal.Cast<TFrom, TTo>()。它可以让您轻松地从 byte/short/int/long 数组更改为结构并返回。

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