5

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?
Tedd Hansen
  • 12,074
  • 14
  • 61
  • 97
  • Maybe using [`IndexOf`](https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.indexof?view=netcore-3.1) method from `MemoryExtensions`? – Pavel Anikhouski Apr 28 '20 at 12:33
  • No, IndexOf is for searching for content. Span can be 1 byte and buffer can be 100 MB, so the information from IndexOf would not tell me anything useful. I could use IndexOf and index all hits, change first value of span and check all the hits for the one that changed. But this is a bit inefficient way of doing it, and defeats the whole purpose of Span. :P – Tedd Hansen Apr 28 '20 at 12:36
  • 2
    `int elementOffsetOf(Span span, T[] array) => (int) Unsafe.ByteOffset(ref array[0], ref span[0]) / Unsafe.SizeOf()` would do it (this could potentially become an (`internal`!) extension method of `T[]`). I'm not sure there's not a more elegant way. Note that this produces garbage if you don't pass a `span` that actually points to an element of `array`; making sure this is the case is your own responsibility, though checks could be added (at some cost). – Jeroen Mostert Apr 29 '20 at 12:30

0 Answers0