brutal/samples/Hello/HelloMemory.cs
Rian Drake b0c9fd9cdc samples: add Hello/Demo samples for most BRUTAL packages
Add samples/, a collection of single-file .NET 10 apps run with
`dotnet run <file>.cs`. Hello/ has one minimal sample per package
that has a public API, many of them headless; Demo/ has fuller
programs that combine packages into a more interesting application.

samples/README.md indexes every sample and covers the layout, error
handling and per-OS requirements.
2026-10-18 18:06:00 +13:00

31 lines
904 B
C#

/*
* HelloMemory
*
* Allocates, uses and frees unmanaged memory with Mem, and owns a pointer with PtrOwner.
*/
#:package Ahwoo.Brutal.Memory@2026.10.1
#:package Ahwoo.Brutal.Core@2026.10.1
// RIAN: This package is due for a big update for custom allocators.
using Brutal;
using Brutal.Memory;
Run();
static void Run()
{
// Allocate 8 ints of unmanaged memory and use it as a Span. It isn't owned by anything, so free it yourself.
var numbers = Mem.AllocZeroed<int>(new ElementCount(8));
for (var i = 0; i < numbers.Length; i++)
numbers[i] = i * i;
Console.WriteLine($"Squares: {string.Join(", ", numbers.ToArray())}");
Console.WriteLine($"Allocated {ByteSize.Of(numbers)} unmanaged");
Mem.Free(numbers);
// PtrOwner frees its allocation when disposed.
using var pi = new PtrOwner<double>(Math.PI);
Console.WriteLine($"PtrOwner holds {pi.Value}");
}