Home >Backend Development >C++ >How to Efficiently Convert C/C Data Structures from Byte Arrays to C# Structures?

How to Efficiently Convert C/C Data Structures from Byte Arrays to C# Structures?

DDD
DDDOriginal
2025-01-19 07:24:11824browse

How to Efficiently Convert C/C   Data Structures from Byte Arrays to C# Structures?

Read C/C data structure from byte array to C#

In C#, when receiving byte array data from a C/C structure, you need to convert the array into a compatible C# structure. The following methods provide an efficient conversion path.

Use Marshal.PtrToStructure

This method involves fixing a byte array and using Marshal.PtrToStructure to convert the bytes directly into a C# structure.

<code class="language-csharp">NewStuff ByteArrayToNewStuff(byte[] bytes)
{
    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    try
    {
        NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));
        return stuff;
    }
    finally
    {
        handle.Free();
    }
}</code>

Universal version

This generic version allows conversion of any struct type from a byte array:

<code class="language-csharp">T ByteArrayToStructure<T>(byte[] bytes) where T : struct 
{
    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    try
    {
        return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    }
    finally
    {
        handle.Free();
    }
}</code>

Simplified version

For simple applications, use unsafe fixed arrays:

<code class="language-csharp">unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
    fixed (byte* ptr = &bytes[0])
    {
        return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T));
    }
}</code>

Comparison of BinaryReader and Marshal.PtrToStructure

BinaryReader functions similarly to Marshal.PtrToStructure, allowing reading data from byte arrays. However, it incurs some additional overhead and is generally not recommended for performance-critical applications. Marshal.PtrToStructure operates directly on raw bytes without intermediate conversion, so performance is faster.

The above is the detailed content of How to Efficiently Convert C/C Data Structures from Byte Arrays to C# Structures?. 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