Are there any alignment guarantees for .data
declarations?
#69044
-
I'd like to do something like the following, but safely on all architectures. static ReadOnlySpan<byte> data => new byte[] { ... };
MemoryMarshal.Cast<byte, uint>(data); I see that accessing |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
There is no useful guarantee today. (Nit: The alignment has to be guaranteed by the compiler. Runtime cannot do much about it.) Dealing with the alignment guarantees has been a significant part of the work required to make #60948 and associated Roslyn feature happen. Look at the linked issue to see all places that had to be fixed to make the alignment work. |
Beta Was this translation helpful? Give feedback.
-
You're absolutely right to raise concern about alignment, especially when working with low-level constructs like
🔍 BackgroundIn .NET (and C# generally), alignment of static fields (even for readonly spans initialized from arrays) is not controlled by the runtime. The JIT or the compiler (Roslyn, RyuJIT) may or may not place such data with natural alignment. Jon’s note about alignment being a compiler responsibility is spot-on — the runtime can’t influence field layout of pre-initialized static data.
|
Beta Was this translation helpful? Give feedback.
There is no useful guarantee today. (Nit: The alignment has to be guaranteed by the compiler. Runtime cannot do much about it.)
Dealing with the alignment guarantees has been a significant part of the work required to make #60948 and associated Roslyn feature happen. Look at the linked issue to see all places that had to be fixed to make the alignment work.