Last active
July 27, 2020 14:34
-
-
Save Const-me/fe69e0a3713f0489b0a7ba5809425d2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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