Can I get a pointer to a Span?
Try this:
Span<byte> bytes = ...;
string s = Encoding.UTF8.GetString((byte*)Unsafe.AsPointer(ref bytes.GetPinnableReference()),
bytes.Length);
If you have C# 7.3 or later, you can use the extension made to the fixed
statement that can use any appropriate GetPinnableReference
method on a type (which Span
and ReadOnlySpan
have):
fixed (byte* bp = bytes) {
...
}
As we're dealing with pointers this requires an unsafe
context, of course.
C# 7.0 through 7.2 don't have this, but allow the following:
fixed (byte* bp = &bytes.GetPinnableReference()) {
...
}