When transmitting data over the network or storing it in a binary file, it is often necessary to convert the structure into a byte array. A structure is a value type that contains multiple related data elements, while a byte array is a continuous block of binary data.
Consider the following C# structure representing a CIFS (Common Internet File System) packet:
<code class="language-csharp">public struct CIFSPacket { // ... various fields ... public string Buffer; }</code>
To convert a structure into a byte array, you can use the StructToPtr method of the Marshal class. This method accepts two parameters:
The following is a function that converts a CIFSPacket structure into a byte array:
<code class="language-csharp">public static byte[] getBytes(CIFSPacket str) { int size = Marshal.SizeOf(str); byte[] arr = new byte[size]; IntPtr ptr = IntPtr.Zero; try { ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(str, ptr, true); Marshal.Copy(ptr, arr, 0, size); } finally { Marshal.FreeHGlobal(ptr); } return arr; }</code>
To marshal strings correctly we need to use the MarshalAs attribute. For example, if our Buffer field is a string, we can annotate it as follows:
<code class="language-csharp">[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)] public string Buffer;</code>
This attribute indicates that the string should be marshalled into a fixed-length, null-terminated string with a maximum size of 100 characters.
Once we have the byte array representation of the structure, we can restore the structure using the PtrToStructure method of the Marshal class. This method accepts two parameters:
The following is a function that converts a byte array back to a CIFSPacket structure:
<code class="language-csharp">public static CIFSPacket fromBytes(byte[] arr) { CIFSPacket str = new CIFSPacket(); int size = Marshal.SizeOf(str); IntPtr ptr = IntPtr.Zero; try { ptr = Marshal.AllocHGlobal(size); Marshal.Copy(arr, 0, ptr, size); str = (CIFSPacket)Marshal.PtrToStructure(ptr, str.GetType()); } finally { Marshal.FreeHGlobal(ptr); } return str; }</code>
To use these functions, simply pass the CIFSPacket structure to the getBytes function to obtain its byte array representation. Alternatively, you can pass a byte array to the fromBytes function to recreate the original structure.
By leveraging marshalling technology, we can easily convert structures into byte arrays and back, allowing for efficient data transmission and storage.
The above is the detailed content of How to Convert C# Structures to and from Byte Arrays using Marshaling?. For more information, please follow other related articles on the PHP Chinese website!