Curious about struct layout and packing
toupswork opened this issue · 8 comments
Hey, man. I was reading up on .NET struct memory layout, and I remembered something about your struct that I was curious about. Why do you declare your struct to have sequential layout while at the same time ordering the fields in a way that, with packing, causes it to have 4 bytes of wasted space on x64, especially since it's not intended to be used in an array?
To be honest it is a while ago and if I recall my memory correctly I did this for cache lining.
But yes it could be revisited if this was a good decision or not
The struct size is well below the 64byte cacheline size, so that had me wondering. Ok cool👍
I've been coding in C# since .NET first came out, and a couple of months ago I saw three POCs that blew my mind. I was wondering if you heard about them. There was a guy who managed to build a C# app stripped down without the base class library and, using Native AOT, wrote a simple kernel mode driver in C# for Windows. He also wrote, using a similar technique, the old retro Snake game in C# that you could boot up your computer into with just UEFI and no OS. Then he managed to link in a stub that allowed it to run in MS DOS. Obviously he couldn't allocate any reference types on the managed heap and used either the stack or marshalled from the unmanaged heap or, for kernel modez use any API that would translate to a pinvoke call to a user mode library. Anyway, Mind blown 🤯.
Wow - do you, by any chance, have done links for that? That sounds very interesting!
I wasn’t even aware you can go THAT far with .net alone.
and also big thanks for raising such good questions! It is really nice when someone asks such intelligent questions to challenge the ideas.
love it!
Sure here is an article on the Snake game. So this can only be accomplished due to UEFI which is the modern BIOS written in C++. The game PInvokes UEFI C++ libraries to do everything. So there is no need to raise software interrupts like you did on older BIOS, which obviously you couldn't do directly in C#. Because he got rid of the BCL, he had to create fake BCL classes as standins for the real ones.
https://migeel.sk/blog/2020/01/03/building-a-self-contained-game-in-csharp-under-8-kilobytes/
And then here is the Kernel mode driver. The key with this is that you must strip .NET down bare and avoid performing anything that can result in a call to a user mode library. Even still, there's very little you can do besides hello world, but the mere fact that C# can run in Kernel mode is truly astounding
Nice - thanks!
Something to read and for sure when I am back from vacation something to play around with!
Really much appreciated
sure fun chatting. enjoy it