Home > Backend Development > C++ > How to Convert a C# Structure to a Byte Array Using Marshaling?

How to Convert a C# Structure to a Byte Array Using Marshaling?

Mary-Kate Olsen
Release: 2025-01-24 14:57:13
Original
941 people have browsed it

How to Convert a C# Structure to a Byte Array Using Marshaling?

In the C#, the structure is converted into byte array

In C#, converting the structure into byte array is a common technique for network data transmission or binary data storage. This guide will demonstrate how to use Marshaling to complete this operation.

The code you provide defines a structure called Cifspacket, which contains various fields that represent the network data packet. To convert this structure to byte array, follow the following steps:

<code class="language-csharp">using System.Runtime.InteropServices;

// 将结构体转换为字节数组的函数
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;
}

// 将字节数组转换为结构体的函数
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>
Copy after login
Please note that for the buffer string field in Cifspacket, you may need to specify the Marshaling property to make it use it correctly with Marshaling. The following is an example:

<code class="language-csharp">[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string Buffer;</code>
Copy after login
Remember, set the sizeConst value according to the maximum expected size of the buffer string.

With these functions, you can use getbytes () to easily convert the Cifspacket structure to byte array, and use Frombytes () to convert it back from the byte array. This provides a convenient method to operate and transmit your structure in binary formats.

The above is the detailed content of How to Convert a C# Structure to a Byte Array Using Marshaling?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template