Home >Backend Development >C++ >How to Convert C# Structures to Byte Arrays for Socket Communication?

How to Convert C# Structures to Byte Arrays for Socket Communication?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-24 14:41:12957browse

How to Convert C# Structures to Byte Arrays for Socket Communication?

Conversion between structure and byte array in C#

When performing socket communication in C#, you need to convert the structure into a byte array. This is achieved through the Marshaling mechanism.

Structure definition

Consider the following structure:

<code class="language-csharp">public struct CIFSPacket
{
    // 字段定义...
    public string Buffer;
}</code>

Marshaling (Serialization)

The Marshal class provides methods for marshaling data between managed and unmanaged code. Convert structure to byte array:

<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;
}</code>

Unmarshalling (deserialization)

Convert byte array back to 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>

Marshaling of string

When marshaling a string in a structure, be sure to specify the representation of the string using the [MarshalAs] attribute. For fixed-length strings like Buffer in the example struct, use:

<code class="language-csharp">[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string Buffer;</code>

Where 100 is replaced by the maximum string length.

Summary

By using Marshaling, you can easily convert the structure into a byte array for data transmission. This technique is commonly used in network applications, such as sending and receiving messages over sockets.

The above is the detailed content of How to Convert C# Structures to Byte Arrays for Socket Communication?. 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