Hacker News new | ask | show | jobs
by neonsunset 500 days ago
It's as if you didn't bother reading my previous comment. Incredible.
1 comments

You keep ignoring the point. Show me how can I write a program in C# that works with a fixed size memory region, lets say 512KB. It should not do any dynamic memory allocation.

Here's a library that does this in C in case you are wondering: https://github.com/rxi/microui.

Sigh.

  // Please, just allocate a normal array instead, there is no benefit to this if it lives throughout the whole application lifetime
  var bytes = (stackalloc byte[512 * 1024]);

  // or, but, please, at least use a span instead of C nonsense of tracking offsets by hand
  // it's not 1980 anymore
  var ptr = stackalloc byte[512 * 1024]; // byte*

  // or
  [InlineArray(256 * 1024)]
  struct CommandList { byte _; }

  var commands = new CommandList();

  // or
  unsafe struct State
  {
    public fixed byte CommandList[256 * 1024];
  }
Whichever you like the most, they do have somewhat different implications - stackalloc is C alloca while struct-based definitions have the exact same meaning as in C.

To avoid running into stack space limitations, you can place a fixed buffer or any of these large arrays into a static field. It gets a fixed static offset in the memory.

C# goes much further and also provides zero-cost abstractions via struct generics with interface constraints. Or without - you can also apply pattern matching against a generic T struct and it will be zero-cost and evaluated at compilation (be it with RyuJIT or ILC (IL AOT Compiler)).

Nice, thanks a lot for sharing the knowledge.