Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jan 6, 2026

Users attempting to use StructLayoutAttribute.Size to create fixed-size buffers encounter memory corruption because the Size property only affects unmanaged layout, not managed memory allocation for non-blittable types.

Changes

  • customize-struct-marshalling.md: Added "Fixed-size buffers and inline arrays" section

    • Warns against using StructLayoutAttribute.Size for fixed-size buffers
    • Explains technical limitation: only affects managed layout for blittable types
    • Provides dangerous vs. safe example using InlineArrayAttribute
    • Cross-references C# language documentation
  • apply-interop-attributes.md: Added cross-reference to InlineArrayAttribute in the StructLayoutAttribute table entry

Example

// ❌ Dangerous: only allocates 1 byte, corrupts memory beyond
[StructLayout(LayoutKind.Explicit, Size = 100)]
struct UnsafeBuffer
{
    [FieldOffset(0)]
    private byte b;
}

// ✔️ Safe: allocates full 100 bytes
struct SafeBuffer
{
    private Buffer100 buffer;
}

[InlineArray(100)]
internal struct Buffer100
{
    private byte _element0;
}
Original prompt

Please implement the suggestion from the user in the last common on this page: dotnet/runtime#112104


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Co-authored-by: agocke <515774+agocke@users.noreply.github.com>
Co-authored-by: agocke <515774+agocke@users.noreply.github.com>
Copilot AI changed the title [WIP] Implement user suggestion from issue 112104 Document InlineArrayAttribute as the correct approach for fixed-size buffers Jan 6, 2026
Copilot AI requested a review from agocke January 6, 2026 00:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants