Hacker News new | ask | show | jobs
by neonsunset 409 days ago
Structs in C# or F# are not low-level per se, they simply are a choice and used frequently in gamedev. So is stackalloc because using it is just 'var things = (stackalloc Thing[5])' where the type of `things` is Span<Thing>. The keyword is a bit niche but it's very normal to see it in code that cares about avoiding allocations.

Note that going more hands-on with these is not the same as violating memory safety - C# even has ref and byreflike struct lifetime analysis specifically to ensure this not an issue (https://em-tg.github.io/csborrow/).

1 comments

Right, it depends on how far one wants to go to avoid allocations. structs and spans are safe. But one can go even deeper and pin pointers and do Unsafe.AsPointer and get a de-facto (unsafe) union out of it....

>https://em-tg.github.io/csborrow/

Oooh... I didn't know scoped refs existed.

If you want an unsafe union, that's what StructLayout.Explicit and FieldOffset is for - a struct with all fields placed at offset 0 is exactly the same as a C union.