How to convert structure to byte array in C # .net, but structure size defined only at runtime

I have a structure as shown below

[StructLayout(LayoutKind.Sequential)] public struct MyStructType { [MarshalAs(UnmanagedType.U1)] public byte stx; public UInt16 cmdId; public UInt16 status; public UInt16 pktNo; [MarshalAs(UnmanagedType.U1)] public byte contPkt; [MarshalAs(UnmanagedType.U1)] public byte dataoffset; public UInt16 dataLength; [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)] public byte[] data; public UInt16 checkSum; [MarshalAs(UnmanagedType.U1)] public byte cr; } 

I tried to convert this structure to an array of bytes using the code below.

 byte[] ConvertStructureToByteArray(MyStructType str) { int size = Marshal.SizeOf(str); byte[] arr = new byte[size]; IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(str, ptr, true); Marshal.Copy(ptr, arr, 0, size); Marshal.FreeHGlobal(ptr); return arr; } 

but I got an error below because the size they do not know

The type "MyStructType" cannot be marshaled as an unmanaged structure; no significant size or bias.

problem due

 public UInt16 dataLength; [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)] public byte[] data; 

dataLength is computed at runtime. How to convert this structure to ByteArray?

+5
source share
1 answer

Marshalling limits

As you already noticed, Marshal.SizeOf() cannot calculate the size of the structure containing the byte array with UnmanagedType.LPArray . However, this does not mean that you cannot calculate it yourself.

However, even if you do, you will receive a Marshal.StructureToPtr complaint about the data field that SafeArray or ByValArray should use.

You should check this on MSDN to understand how to transfer arrays from managed to unmanaged. However, it seems that for the arrays contained in the structure :

Size can only be set as a constant

Why not use serialization?

The Buffer protocol is an easy way to serialize data to a binary file. In addition, it supports model change, model share and several other interesting features.

It is available in several languages:

0
source

Source: https://habr.com/ru/post/1238355/


All Articles