Streamlining C# Structure to Byte Array Conversion for Network Transmission
Efficiently transmitting structured data across networks often requires converting C# structures into byte arrays. While structures group related data, they aren't directly compatible with binary network transmission.
Let's illustrate with an example:
<code class="language-csharp">public struct CIFSPacket { public uint protocolIdentifier; public byte command; // ... other fields }</code>
To transform a CIFSPacket
instance (packet
) into a byte array, follow these steps:
using System.Runtime.InteropServices;
to your code.Marshal.SizeOf(packet)
.IntPtr ptr = Marshal.AllocHGlobal(size);
.Marshal.StructureToPtr(packet, ptr, true);
.byte[] arr = new byte[size]; Marshal.Copy(ptr, arr, 0, size);
.Marshal.FreeHGlobal(ptr);
.This process converts the structure into a network-ready byte array.
The reverse process (byte array to structure) is equally straightforward:
<code class="language-csharp">public CIFSPacket FromBytes(byte[] arr) { CIFSPacket str = new CIFSPacket(); int size = Marshal.SizeOf(str); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.Copy(arr, 0, ptr, size); str = (CIFSPacket)Marshal.PtrToStructure(ptr, str.GetType()); Marshal.FreeHGlobal(ptr); return str; }</code>
For string fields within your structures, use the [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
attribute, replacing 100
with the maximum string length.
This method ensures reliable structure-to-byte array conversion for robust network communication.
The above is the detailed content of How to Efficiently Convert C# Structures to Byte Arrays for Network Communication?. For more information, please follow other related articles on the PHP Chinese website!