// Generated from executable documentation examples. Edit the source region, then regenerate. using System; using System.IO; using System.IO.Pipelines; using System.Linq; using System.Buffers; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.Numerics; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using CStructSharp; using CStructSharp.Codecs; using CStructSharp.Diagnostics; using CStructSharp.Introspection; using CStructSharp.Values; internal static partial class Program { public static void Main() { WindowsHeader(); Console.WriteLine("PASS windows-header"); } private static void WindowsHeader() { // A header pasted from a Windows SDK or a dissect definition: SDK spellings, a repeated `_` padding // field, a tagged inline union whose members are promoted, and a pointer-to-string alias. const string definition = """ typedef struct _RECORD { DWORD Magic; WORD Version; WORD _; union version_information { DWORD Packed; struct { BYTE Major; BYTE Minor; WORD Build; }; }; DWORD _; PWSTR Name; } RECORD, *PRECORD; """; var layout = new CStruct(definition, pointerSize: 4, aligned: true); byte[] bytes = [0x4D, 0x5A, 0x00, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0x0A, 0x00, 0x39, 0x30, 0xEE, 0xEE, 0xEE, 0xEE, 0x00, 0x00, 0x00, 0x00]; StructValue record = layout.Parse(bytes, "RECORD"); Equal(0x5A4DU, record.Get("Magic")); Equal((ushort)2, record.Get("Version")); Equal((byte)10, record.Get("Major")); Equal((ushort)12345, record.Get("Build")); Equal(0x3039000AU, record.Get("Packed")); True(!record.ContainsKey("_"), "padding is not a member"); // The tag, the alias, and the pointer alias all name the same declaration; the promoted union writes // back through the member the data supplies and the padding as zeroes. Equal(20, layout.GetStructSizeInBytes("_RECORD")); byte[] written = layout.Serialize("RECORD", new Dictionary { ["Magic"] = 0x5A4DU, ["Version"] = (ushort)2, ["Packed"] = 0x3039000AU, ["Name"] = 0U }); SequenceEqual([0x4D, 0x5A, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x39, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], written); } private static void Equal(T expected, T actual) { if (!EqualityComparer.Default.Equals(expected, actual)) { throw new InvalidOperationException($"Expected '{expected}', received '{actual}'."); } } private static void True(bool condition, string message) { if (!condition) { throw new InvalidOperationException(message); } } private static void SequenceEqual(byte[] expected, byte[] actual) { if (!expected.AsSpan().SequenceEqual(actual)) { throw new InvalidOperationException( $"Expected {Convert.ToHexString(expected)}, received {Convert.ToHexString(actual)}."); } } }