Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we use NativeMemory.Alloc() in .NET? [closed]

Tags:

c#

.net-6.0

.NET6/C# introduced NativeMemory class, but I did not get when we should use NativeMemory.Alloc() instead of normal array instantiation(new T[]). My questions are:

  1. Which area on memory does NativeMemory.Alloc() populate objects? Does the method populate objects in managed heap?

  2. What kind of situation should we use NativeMemory.Alloc() on behalf of new T[]?

Reference: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.nativememory?view=net-6.0

like image 472
shumach5 Avatar asked Apr 08 '26 01:04

shumach5


1 Answers

Looks like it's a "thin wrapper over the C malloc API." So if I'm recalling correctly it would allocate memory on the unmanaged heap.

As for the second question, I can't really think of any specific scenarios (save for some edge-cases) where that would be useful (though I'm sure they exist) in .NET where one wouldn't already be using C/C++. That aside though, I suppose one would use this where speed is absolutely paramount (such as rendering).

It's just been added so that we'd have the option to use C/C++ like memory management.

like image 68
gam03 Avatar answered Apr 10 '26 14:04

gam03



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!