# How Glass reconstructs a native interop struct


A P/Invoke struct carries a contract that is not written down anywhere in the C# you see. `[StructLayout(LayoutKind.Sequential, Pack = 1)]` and a few `[MarshalAs(...)]` attributes decide, down to the byte, what block of memory the runtime hands to native code. Get the layout wrong and the call still compiles, still runs, and silently corrupts memory. So when you open an unfamiliar assembly to understand — or verify — an interop boundary, the first thing you need back is that exact native shape.

Here is the surprise: those attributes are not in the assembly. Not as attributes, anyway.

## The real question

Open any decompiler on a struct decorated with `[MarshalAs]` and it shows the attributes right back to you. That looks trivial — read the custom attribute, print it. But the CLR never stored a custom attribute. `StructLayoutAttribute`, `MarshalAsAttribute`, `FieldOffsetAttribute` and a handful of others are **pseudo-custom attributes**: the compiler reads them at build time, deletes them, and writes their meaning into dedicated metadata tables instead. There is no blob in the `CustomAttribute` table to print.

So the real question is: if the attribute is gone, how does Glass put it back — correctly, with the right `SizeConst`, the right `UnmanagedType`, the right char width? The answer is a small, exact reverse mapping from two metadata tables, and it is worth understanding because it is also what tells you the true native contract.

## A struct with a real native shape

Take a struct that mirrors a C `DeviceInfo` returned by a device-enumeration API you have the headers for:

```csharp
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct DeviceInfo
{
    public uint Size;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string Name;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
    public byte[] MacAddress;

    [MarshalAs(UnmanagedType.I1)]
    public bool IsOnline;
}
```

The native contract this describes is precise:

```c
#pragma pack(1)
struct DeviceInfo {
    uint32_t Size;          // 4 bytes
    wchar_t  Name[32];      // 32 * 2 = 64 bytes (CharSet.Unicode)
    uint8_t  MacAddress[6]; // 6 bytes, inline
    int8_t   IsOnline;      // 1 byte (I1), not the default 4-byte BOOL
};                          // Pack = 1 -> no padding -> 75 bytes total
```

Every number there comes from the attributes. `ByValTStr` makes `Name` an *inline* fixed buffer of 32 characters rather than a pointer to a string; `CharSet.Unicode` makes each character 2 bytes; `ByValArray` inlines 6 bytes where the default would marshal `byte[]` as a pointer; and `[MarshalAs(I1)]` shrinks `bool` from its 4-byte Win32 default to a single byte. Lose any one of those and the struct is a different size and the fields land at different offsets.

## Where the compiler actually put it

Compile that and look at the metadata, not the IL. Three things changed, none of them a custom attribute.

**1. The TypeDef flags.** `LayoutKind.Sequential` sets `tdSequentialLayout`; `CharSet.Unicode` sets `tdUnicodeClass`. The class header carries them directly:

```
.class public sequential unicode sealed beforefieldinit DeviceInfo
       extends [System.Runtime]System.ValueType
{
  .pack 1
  .size 0
```

**2. The `ClassLayout` table (0x0F).** `Pack` and any explicit size live here, one row keyed to the TypeDef:

```
ClassLayout
  Parent        PackingSize   ClassSize
  DeviceInfo    1             0
```

`PackingSize = 1` is the `Pack = 1`. `ClassSize = 0` means "compute it from the fields" — the runtime adds them up under the packing rule.

**3. The `FieldMarshal` table (0x0D).** This is the heart of it. Each `[MarshalAs]` becomes one row: a `Parent` (a coded index pointing at the field) and a `NativeType` (an index into the blob heap). The blob is a *marshalling descriptor* — a tiny byte script in the `NATIVE_TYPE_*` encoding from ECMA-335:

```
FieldMarshal
  Parent (field)   NativeType blob
  Name             17 20          ; FIXEDSYSSTRING(0x17), SizeConst = 0x20 (32)
  MacAddress       1e 06 04       ; FIXEDARRAY(0x1e), count = 6, element U1(0x04)
  IsOnline         03             ; I1(0x03)
```

Those bytes are the whole contract. `0x17` is `NATIVE_TYPE_FIXEDSYSSTRING` (what C# spells `ByValTStr`) and the `0x20` after it is the compressed element count. `0x1e` is `NATIVE_TYPE_FIXEDARRAY`, followed by the count and the element's native type. `0x03` is `NATIVE_TYPE_I1`. There is no `MacAddress` field without a `FieldMarshal` row for the fields that have no attribute — `Size` simply does not appear in the table, which is itself information: no row means default marshalling.

<figure class="my-8"><svg viewBox="0 0 760 360" role="img" aria-label="Metadata tables map back to a reconstructed interop struct" xmlns="http://www.w3.org/2000/svg"><rect x="0" y="0" width="760" height="360" fill="none"/><text x="20" y="28" fill="#6366f1" font-family="monospace" font-size="15" font-weight="bold">Metadata the compiler wrote</text><rect x="20" y="42" width="300" height="60" rx="6" fill="none" stroke="#0891b2" stroke-width="1.5"/><text x="32" y="64" fill="#0891b2" font-family="monospace" font-size="12" font-weight="bold">TypeDef flags</text><text x="32" y="84" fill="#64748b" font-family="monospace" font-size="11">sequential | unicode | sealed</text><rect x="20" y="114" width="300" height="60" rx="6" fill="none" stroke="#0891b2" stroke-width="1.5"/><text x="32" y="136" fill="#0891b2" font-family="monospace" font-size="12" font-weight="bold">ClassLayout</text><text x="32" y="156" fill="#64748b" font-family="monospace" font-size="11">PackingSize=1  ClassSize=0</text><rect x="20" y="186" width="300" height="118" rx="6" fill="none" stroke="#0891b2" stroke-width="1.5"/><text x="32" y="208" fill="#0891b2" font-family="monospace" font-size="12" font-weight="bold">FieldMarshal (blob)</text><text x="32" y="230" fill="#64748b" font-family="monospace" font-size="11">Name       17 20</text><text x="32" y="250" fill="#64748b" font-family="monospace" font-size="11">MacAddress 1e 06 04</text><text x="32" y="270" fill="#64748b" font-family="monospace" font-size="11">IsOnline   03</text><text x="32" y="292" fill="#64748b" font-family="monospace" font-size="10">(no row = default marshalling)</text><path d="M330 150 L430 150" stroke="#10b981" stroke-width="2" fill="none" marker-end="url(#ar)"/><defs><marker id="ar" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"><path d="M0 0 L7 3 L0 6 Z" fill="#10b981"/></marker></defs><text x="340" y="140" fill="#10b981" font-family="monospace" font-size="11">Glass</text><text x="340" y="165" fill="#10b981" font-family="monospace" font-size="11">reverse-maps</text><rect x="440" y="42" width="300" height="262" rx="6" fill="none" stroke="#6366f1" stroke-width="1.5"/><text x="452" y="64" fill="#6366f1" font-family="monospace" font-size="12" font-weight="bold">Reconstructed C#</text><text x="452" y="88" fill="#64748b" font-family="monospace" font-size="11">[StructLayout(Sequential,</text><text x="452" y="106" fill="#64748b" font-family="monospace" font-size="11">  Pack=1, CharSet=Unicode)]</text><text x="452" y="130" fill="#64748b" font-family="monospace" font-size="11">uint Size;</text><text x="452" y="154" fill="#64748b" font-family="monospace" font-size="11">[MarshalAs(ByValTStr,</text><text x="452" y="172" fill="#64748b" font-family="monospace" font-size="11">  SizeConst=32)] string Name;</text><text x="452" y="196" fill="#64748b" font-family="monospace" font-size="11">[MarshalAs(ByValArray,</text><text x="452" y="214" fill="#64748b" font-family="monospace" font-size="11">  SizeConst=6)] byte[] MacAddress;</text><text x="452" y="238" fill="#64748b" font-family="monospace" font-size="11">[MarshalAs(I1)] bool IsOnline;</text><text x="452" y="276" fill="#10b981" font-family="monospace" font-size="11">native size = 75 bytes</text></svg><figcaption class="text-sm text-muted mt-2">The attributes are gone from the IL; Glass rebuilds them from the TypeDef flags, ClassLayout, and the FieldMarshal blob descriptors.</figcaption></figure>

## The reverse mapping, step by step

Glass walks the three sources and composes one attribute set per field and one per type.

For the **type**, it reads the layout bit from the TypeDef flags (`tdSequentialLayout` → `LayoutKind.Sequential`, `tdExplicitLayout` → `Explicit`, neither → `Auto`) and the charset bits (`tdUnicodeClass` → `CharSet.Unicode`, `tdAnsiClass` → `Ansi`, `tdAutoClass` → `Auto`). It joins the `ClassLayout` row to pull `Pack` and, if non-zero, `Size`. Those become the `[StructLayout(...)]` arguments.

For each **field**, it looks for a `FieldMarshal` row whose `Parent` resolves to that field. If there is none, the field marshals by default and gets no attribute. If there is one, Glass decodes the blob: the first byte is the `UnmanagedType`, and depending on which one it is, zero or more operands follow. `0x17` (`ByValTStr`) takes a count → `SizeConst`. `0x1e` (`ByValArray`) takes a count and an element native type → `SizeConst` plus, where the element type is not the obvious default, `ArraySubType`. Scalars like `0x03` (`I1`) take nothing. The decoded result is emitted as `[MarshalAs(UnmanagedType.X, ...)]`.

The payoff is that the recovered struct is not a guess. The 75-byte figure, the 2-byte characters, the single-byte bool — all of it is reconstructed from bytes the compiler committed, so Glass can show the native size alongside the type. That number is the thing you actually came for when you are checking an interop boundary against a C header.

## When the recovery is partial

The honest limits are all about information the metadata genuinely does not keep.

- **Field *names* in a sequential or explicit layout are not load-bearing for marshalling**, but they are still real field names and survive. What does not survive is anything the attribute *computed* rather than stored. `LayoutKind.Auto` structs carry no `ClassLayout` and no field order guarantee, so there is nothing to recover beyond the flag.
- **Variable-length arrays lose their literal size.** `UnmanagedType.LPArray` with a `SizeParamIndex` encodes a parameter index in the blob, not a constant, so Glass recovers `SizeParamIndex = n`, which is exactly what was there — but there is no `SizeConst` to show.
- **Default marshalling is invisible by design.** A `byte[]` with no `[MarshalAs]` marshals as a pointer. Glass correctly emits no attribute, but a reader expecting an inline buffer has to know that the *absence* of a row means "pointer, not inline". That is a property of the platform, not a gap in the decompiler.
- **`[StructLayout]` with `CharSet.Auto`** means the native width of string fields depends on the OS the code runs on. Glass can only show `Auto`; it cannot tell you which width a given deployment resolved to.

## Takeaway

The attributes that define an interop contract are compiled *away* — `StructLayout` into TypeDef flags and a `ClassLayout` row, each `MarshalAs` into a `FieldMarshal` blob. A decompiler that only prints custom attributes would show you a struct with none of this, which is worse than useless at an interop boundary. Glass.NET reverse-maps the real tables, decodes the `NATIVE_TYPE_*` descriptors, and reconstructs the exact attributes and the native byte size — so what you read back is the contract native code actually sees. Glass is a free .NET decompiler; you can inspect any assembly you have the right to analyze, from the [Glass.NET product page](https://delta1labs.com/products/glass) or the [CLI and MCP docs](https://delta1labs.com/docs/glass/).

