I have a (ReadOnly)Span<byte>
from which I want to decode a string.
Only in .NET Core 2.1 I have the new overload to decode a string from it without needing to copy the bytes:
Encoding.GetString(ReadOnlySpan<byte> bytes);
In .NET Standard 2.0 and .NET 4.6 (which I also want to support), I only have the classic overloads:
Encoding.GetString(byte[] bytes);
Encoding.GetString(byte* bytes, int byteCount);
The first one requires a copy of the bytes into an array which I want to avoid.
The second requires a byte pointer, so I thought about getting one from my span, like
Encoding.GetString(Unsafe.GetPointer<byte>(span.Slice(100)))
...but I failed finding an actual method for that. I tried void* Unsafe.AsPointer<T>(ref T value)
, but I cannot pass a span to that, and didn't find another method dealing with pointers (and spans).
Is this possible at all, and if yes, how?
[ReadOnly]Span<T>.GetPinnableReference()
. If using C# 7.3, leveraging this is as simple asfixed (byte* bytes = span)
-- this compiles for .NET 4.5.2, at least, I haven't tested if it will also really work (I only have later frameworks installed). – Retractileref GetPinnableReference()
as the argument toUnsafe.AsPointer
. You need at least C# 7.0 to useref
locals. – Retractile