Earlier quoted context omitted.
A rather useful pattern in C# is to load a blob into a byte array, then inside unsafe code, typecast it to a pointer to well-defined struct. There's also managed ways to do that, but they are slower and involve copying memory.
Any chance you have an example of this pattern you can point to? Also, would the use of Span make it possible to do this without unsafe code?
I didn't learn by following someone's example, in my case, I have to work with so many different structs in a high performance use case that I took the time to re-learn pointers. (Haven't used them in years.)
1: Memory is allocated using new byte[bufferSize]
2: That byte[] is pinned to a byte* or void* via fixed
3: The pointer is passed to DeviceIOControl
4: Traditional c-style typecasting inside of fixed
5: Traditional GC cleans up your byte[]. This avoids problems with managed programs that allocate lots of native memory.
I don't know how to use pointers with Span...
BUT: I do similar things with ArraySegment. All that's needed is pointer arithmetic:
ArraySegment arraySegment = ...
fixed (byte* dataArrayPtr = arraySegment.Array)
{
var dataPtr = dataArrayPtr + arraySegment.Offset;
var ptr = (SomeStruct*)dataPtr;
}