<p>What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct?  The C struct would look something like this (my C is very rusty):</p>

<pre><code>typedef OldStuff {
    CHAR Name[8];
    UInt32 User;
    CHAR Location[8];
    UInt32 TimeStamp;
    UInt32 Sequence;
    CHAR Tracking[16];
    CHAR Filler[12];
}
</code></pre>

<p>And would fill something like this:</p>

<pre><code>[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
public struct NewStuff
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
    [FieldOffset(0)]
    public string Name;

    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(8)]
    public uint User;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
    [FieldOffset(12)]
    public string Location;

    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(20)]
    public uint TimeStamp;

    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(24)]
    public uint Sequence;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    [FieldOffset(28)]
    public string Tracking;
}
</code></pre>

<p>What is best way to copy <code>OldStuff</code> to <code>NewStuff</code>, if <code>OldStuff</code> was passed as byte[] array?</p>

<p>I'm currently doing something like the following, but it feels kind of clunky.</p>

<pre><code>GCHandle handle;
NewStuff MyStuff;

int BufferSize = Marshal.SizeOf(typeof(NewStuff));
byte[] buff = new byte[BufferSize];

Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);

handle = GCHandle.Alloc(buff, GCHandleType.Pinned);

MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));

handle.Free();
</code></pre>

<p>Is there better way to accomplish this?</p>

<hr>

<p>Would using the <code>BinaryReader</code> class offer any performance gains over pinning the memory and using <code>Marshal.PtrStructure</code>?</p>

[{'answer_id': 2881, 'author': 'Mufaka', 'author_id': 449, 'author_profile': 'https://Stackoverflow.com/users/449', 'pm_score': -1, 'selected': False, 'text': '<p>If you have a byte[] you should be able to use the BinaryReader class and set values on NewStuff using the available ReadX methods.</p>\n'}, {'answer_id': 2887, 'author': 'Coincoin', 'author_id': 42, 'author_profile': 'https://Stackoverflow.com/users/42', 'pm_score': 8, 'selected': True, 'text': "<p>From what I can see in that context, you don't need to copy <code>SomeByteArray</code> into a buffer. You simply need to get the handle from <code>SomeByteArray</code>, pin it, copy the <code>IntPtr</code> data using <code>PtrToStructure</code> and then release. No need for a copy.</p>\n\n<p>That would be:</p>\n\n<pre><code>NewStuff ByteArrayToNewStuff(byte[] bytes)\n{\n    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n    try\n    {\n        NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));\n    }\n    finally\n    {\n        handle.Free();\n    }\n    return stuff;\n}\n</code></pre>\n\n<p>Generic version:</p>\n\n<pre><code>T ByteArrayToStructure&lt;T&gt;(byte[] bytes) where T: struct \n{\n    T stuff;\n    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n    try\n    {\n        stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\n    }\n    finally\n    {\n        handle.Free();\n    }\n    return stuff;\n}\n</code></pre>\n\n<p>Simpler version (requires <code>unsafe</code> switch):</p>\n\n<pre><code>unsafe T ByteArrayToStructure&lt;T&gt;(byte[] bytes) where T : struct\n{\n    fixed (byte* ptr = &amp;bytes[0])\n    {\n        return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T));\n    }\n}\n</code></pre>\n"}, {'answer_id': 36740, 'author': 'Tim Ring', 'author_id': 3685, 'author_profile': 'https://Stackoverflow.com/users/3685', 'pm_score': 3, 'selected': False, 'text': '<p>Watch out for packing issues. In the example you gave all fields are at the obvious offsets because everything is on 4 byte boundaries but this will not always be the case. Visual C++ packs on 8 byte boundaries by default.</p>\n'}, {'answer_id': 8463705, 'author': 'Dushyant', 'author_id': 1092176, 'author_profile': 'https://Stackoverflow.com/users/1092176', 'pm_score': 2, 'selected': False, 'text': '<pre><code>object ByteArrayToStructure(byte[] bytearray, object structureObj, int position)\n{\n    int length = Marshal.SizeOf(structureObj);\n    IntPtr ptr = Marshal.AllocHGlobal(length);\n    Marshal.Copy(bytearray, 0, ptr, length);\n    structureObj = Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(bytearray, position), structureObj.GetType());\n    Marshal.FreeHGlobal(ptr);\n    return structureObj;\n}   \n</code></pre>\n\n<p>Have this</p>\n'}, {'answer_id': 41836532, 'author': 'cdiggins', 'author_id': 184528, 'author_profile': 'https://Stackoverflow.com/users/184528', 'pm_score': 4, 'selected': False, 'text': '<p>Here is an exception safe version of the <a href="https://stackoverflow.com/a/2887/184528">accepted answer</a>: </p>\n\n<pre><code>public static T ByteArrayToStructure&lt;T&gt;(byte[] bytes) where T : struct\n{\n    var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n    try {\n        return (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\n    }\n    finally {\n        handle.Free();\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/2871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/206/']