Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

If you really really want to, you can use Marshal.AllocHGlobal and allocate unmanaged memory. All access happens through pointers and `unsafe` code blocks.


You're supposed to use NativeMemory.Alloc/.Free methods instead.

Obviously nothing prevents you from PInvoking malloc and free directly, or linking to a custom allocator, or even using https://www.nuget.org/packages/TerraFX.Interop.Mimalloc which is a fully managed Mimalloc implementation (which is competitive with the original).

There is also an advanced undocumented API to register a specific segment of memory as nongc-heap where you can allocate otherwise managed objects manually.

But the most important thing to understand that normally in languages with generational GCs the objects are not freed, instead, the surviving objects are copied to an older generation while the rest of the memory is reclaimed and immediately made available for subsequent allocations. As a result, you can't "free" an object since such operation does not exist in the design.

Overall, you're not forced to use objects in low-level code - structs can implement methods, interfaces, used in generics for zero cost abstractions,etc., and if you don't allocate or allocate only a little - the GC will never run.


I didn't realize that the GC copied the surviving objects to a separate location. Come to think of it, i don't actually know how the GC keeps track of what object lies in what generation.


GC is free to move things all over memory, though I'm not savvy enough to say why this is necessary.

C# allows you to "pin" a variable to combat this. Any pinned memory will never be moved by GC, so if you pass a pointer to an object out of your managed program, the pointer address will always stay valid.


If you can't move objects around in memory, you get memory fragmentation.


Modern C# has Span<T> and Memory<T> types to give you the ability to work with unmanaged memory without directly touching pointers or `unsafe`, FWIW. Worth messing with the next time you need to do it.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: