Home >Backend Development >C++ >How to Convert a C# Structure (CIFSPacket) to a Byte Array for Network Transmission?
The conversion of the structure to the byte array in the structure of the byte array
Network data transmission needs to convert the structure to byte array. The following answers describing how to convert a specific structure named Cifspacket in C# to byte array:
Question:
How to convert the CIFSPACKET structure into byte array in order to transmit network transmission by using a piece of word?
Answer:
Marshaling is an effective way to convert this. Implement:
Including header files: Add
to the beginning of the program.
using System.Runtime.InteropServices;
<code class="language-csharp"> 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>
For the string field, specify
<code class="language-csharp"> 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 indicate a string with a maximum size of 100.
Example usage:
Send function:[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
The above is the detailed content of How to Convert a C# Structure (CIFSPacket) to a Byte Array for Network Transmission?. For more information, please follow other related articles on the PHP Chinese website!