Span points to a memory area. Given that I know what memory area it is (i.e. array), can I (efficiently) figure out what first element in the array it is pointing to? I figured since it is pointing to non-pinned memory this information has to be stored somewhere, as address has to be updated by GC.
var buffer = new byte[100];
var span = new Span<byte>(buffer);
span = span.Slice(10, 5);
// How can I figure out where in buffer this span starts?
IndexOf
method fromMemoryExtensions
? – Haggertyint elementOffsetOf<T>(Span<T> span, T[] array) => (int) Unsafe.ByteOffset(ref array[0], ref span[0]) / Unsafe.SizeOf<T>()
would do it (this could potentially become an (internal
!) extension method ofT[]
). I'm not sure there's not a more elegant way. Note that this produces garbage if you don't pass aspan
that actually points to an element ofarray
; making sure this is the case is your own responsibility, though checks could be added (at some cost). – Coelom