converting between struct and byte array
        Posted  
        
            by chonch
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by chonch
        
        
        
        Published on 2010-05-06T00:20:08Z
        Indexed on 
            2010/05/06
            0:28 UTC
        
        
        Read the original article
        Hit count: 652
        
his question is about converting between a struct and a byte array. Many solutions are based around GCHandle.Alloc() and Marshal.StructureToPtr(). The problem is these calls generate garbage. For example, under Windows CE 6 R3 about 400 bytes of garbarge is made with a small structure. If the code below could be made to work the solution could be considered cleaner. It appears the sizeof() happens too late in the compile to work.
public struct Data
{
    public double a;
    public int b;
    public double c;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe struct DataWrapper
{
    private static readonly int val = sizeof(Data);
    [FieldOffset(0)]
    public fixed byte Arr[val]; // "fixed" is to embed array instead of ref
    [FieldOffset(0)]
    public Data; // based on a C++ union
}
© Stack Overflow or respective owner