Replies: 4 comments 8 replies
-
All kinds of struct <-> class reinterpretation-like casts are UB and may lead to hard-to-reproduce crashes/gc holes. |
Beta Was this translation helpful? Give feedback.
-
For case 2, #76169 shows a way to do it using |
Beta Was this translation helpful? Give feedback.
-
The answer to question 1 is yes. The constructor of The answer to question 2 is yes as well, because you assign a boxed |
Beta Was this translation helpful? Give feedback.
-
Re: Definedness of reinterpreting // C# defaults to sequential layout.
public readonly struct Seq { public readonly object O; public Seq(object o) { O = o; } }
[StructLayout(LayoutKind.Explicit)]
public readonly struct Expl
{
[FieldOffset(0)]
public readonly object O;
public Expl(object o) { O = o; }
}
if (sizeof(Seq) != sizeof(object)) Environment.FailFast(null);
if (sizeof(Expl) != sizeof(object)) Environment.FailFast(null);
Seq s = new Seq();
Expl[] e = new Expl[2];
Unsafe.As<Seq, object>(ref s) = new object(); // S
Unsafe.Add(
ref Unsafe.As<Expl, object>(ref e[0]),
1) = new object(); // E Per ECMA-335 edition 6, I.12.1.1 (Native size: native int, native unsigned int, O and &):
This suggests each field of each type as a fixed offset once JIT-ted. Per II.10.7 (Controlling instance layout):
There are 3 possible interpretations of the boldfaced sentence:
In interpretations 2 and 3, the line with comment In all interpretations, the line with comment
OTOH, it's surprising that the spec does not say that a sequential-layout type has its first field at offset |
Beta Was this translation helpful? Give feedback.
-
Hello, I have a few questions regarding the safety of type punning as far as the runtime is concerned.
span[0] = (object)123;
would be undefined behavior. Is this correct?object[]
and fill withIEnumerable
andnull
, and I reinterpret the array storage asReadOnlySpan<IEnumerable>
and read from it. Is there undefined behavior? I think not.Environment.FailFast
is desired in case there's a layout mismatch; otherwise, I expect things to work out).object
, but onlystring
andnull
are stored. Is there undefined behavior? I think not.uint
,nint
,float
,double
,StringSplitOptions
) and no memory is access beyond the storage of the array. Is there undefined behavior? I believe not and what happens is just the bits are tweaked.General.
ref
andUnsafe.Add
instead ofSpan
?I tried reading the docs of .NET memory model but it only deals with multithreaded access, not type punning.
Beta Was this translation helpful? Give feedback.
All reactions