Skip to content

Instantly share code, notes, and snippets.

@Const-me
Last active July 27, 2020 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Const-me/fe69e0a3713f0489b0a7ba5809425d2b to your computer and use it in GitHub Desktop.
Save Const-me/fe69e0a3713f0489b0a7ba5809425d2b to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.InteropServices;
namespace NativeSpan
{
/// <summary>Allows manual memory management without GC in a manner that's still mostly safe</summary>
ref struct NativeSpan<T> where T : unmanaged
{
readonly IntPtr nativePointer;
readonly int length;
public NativeSpan( int length )
{
if( length <= 0 )
throw new ArgumentException();
nativePointer = Marshal.AllocHGlobal( Marshal.SizeOf<T>() * length );
if( nativePointer == default )
throw new OutOfMemoryException();
this.length = length;
}
public void Dispose()
{
Marshal.FreeHGlobal( nativePointer );
}
public Span<T> span
{
get
{
unsafe
{
return new Span<T>( (void*)nativePointer, length );
}
}
}
}
static class Program
{
static void Main( string[] args )
{
using( var ns = new NativeSpan<int>( 11 ) )
{
foreach( ref var i in ns.span )
i = 33;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment