This is an old revision of the document!

C# Marshaling - write bytes to struct and vice versa

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyStructure
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 101)]
    public char[] Name;
    public UInt16 Port;
    public byte Num;
    public byte Max;
    public UInt64 Version;
    public byte TOD;
    public byte Avg;
    public byte Flags;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public char[] Key;
public static MyStructure BytesToMyStructure(Byte[] bytes)
    MyStructure X = new();
    int size = Marshal.SizeOf(X);
    IntPtr ptr = Marshal.AllocHGlobal(size);
    Marshal.Copy(bytes, 0, ptr, size);
    X = (S.EnrollServer)Marshal.PtrToStructure(ptr, X.GetType());
    return X;
public static Byte[] MyStructureToBytes(MyStructure data)
    int size = Marshal.SizeOf(data);
    byte[] bytes = new byte[size];
    IntPtr ptr = Marshal.AllocHGlobal(size);
    Marshal.StructureToPtr(data, ptr, true);
    Marshal.Copy(ptr, bytes, 0, size);
    return bytes;
Enter your comment:
  • development/csharp/marshaling.1621491279.txt.gz
  • Last modified: 2021-05-20 08:14
  • by tplecko