Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions docs/standard/native-interop/customize-struct-marshalling.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ The following example shows the incorrect approach that can lead to memory corru
```csharp
// ❌ DON'T: This is dangerous and can corrupt memory
[StructLayout(LayoutKind.Explicit, Size = 100)]
struct UnsafeBuffer
class Bad100ByteBuffer
{
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
[FieldOffset(0)]
private byte b;
Expand All @@ -48,7 +48,6 @@ struct UnsafeBuffer
{
fixed (byte* p = &b)
{
// This may interpret p as a 100-byte buffer, but only 1 byte is allocated
// Writing beyond the first byte corrupts memory
}
}
Expand All @@ -59,8 +58,14 @@ Instead, use `InlineArrayAttribute` to create a properly sized buffer:

```csharp
// ✔️ DO: Use InlineArrayAttribute for fixed-size buffers
struct SafeBuffer
class Good100ByteBuffer
{
Comment thread
AaronRobinsonMSFT marked this conversation as resolved.
[InlineArray(100)]
private struct Buffer100
{
private byte _element0;
}

private Buffer100 buffer;

unsafe void UseBuffer()
Expand All @@ -71,12 +76,6 @@ struct SafeBuffer
}
}
}

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

For more information about inline arrays, see the [C# language reference](../../csharp/language-reference/builtin-types/struct.md#inline-arrays).
Expand Down
Loading