Home >Backend Development >C++ >How to Convert C# Structures to and from Byte Arrays using Marshaling?

How to Convert C# Structures to and from Byte Arrays using Marshaling?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-24 14:36:14674browse

How to Convert C# Structures to and from Byte Arrays using Marshaling?

Convert structure to byte array in C#

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.

Structure definition

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>

Conversion function

To convert a structure into a byte array, you can use the StructToPtr method of the Marshal class. This method accepts two parameters:

  • Structure: The structure to be converted.
  • Pointer: The starting pointer of the byte array where the converted data will be stored.

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>

String marshalling

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.

Restore structure

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:

  • Pointer: The starting pointer of the byte array containing the structure data.
  • Type: The type of structure to create.

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>

How to use

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!

Statement:
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