Home > Backend Development > C++ > How to Efficiently Convert a C/C Data Structure from a Byte Array to a C# Struct?

How to Efficiently Convert a C/C Data Structure from a Byte Array to a C# Struct?

Mary-Kate Olsen
Release: 2025-01-19 07:36:10
Original
599 people have browsed it

How to Efficiently Convert a C/C   Data Structure from a Byte Array to a C# Struct?

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

This article describes how to fill byte array data derived from C/C structures into C# structures.

Using GCHandle and Marshal

This method is divided into three steps:

  1. Use GCHandle.Alloc to fix the location of the byte array in memory.
  2. Use Marshal.PtrToStructure to convert a fixed memory address to a NewStuff instance.
  3. Once the conversion is complete, use handle.Free() to release GCHandle.

Simplified code:

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

Generic version:

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

More simplified version (requires unsafe code block):

<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>
Copy after login

BinaryReader method

Using BinaryReader may not be more performant than the Marshal method. Both methods require the data to be correctly laid out and sized to be successfully converted into a NewStuff structure.

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