development:csharp:marshaling

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());
    Marshal.FreeHGlobal(ptr);
    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);
    Marshal.FreeHGlobal(ptr);
    return bytes;
}
Enter your comment:
J I L᠎ P V
 
  • development/csharp/marshaling.txt
  • Last modified: 2021-05-20 08:14
  • by tplecko