unmanaged struct issue
Do have experience if in c# casting nint pointers to other pointer types is bad? Like I want to allocate an unmanaged struct. And I just cast the nint pointer returned by NativeMemory / Marshal to T*. Should I be using Span<T> instead?
because I read casting to different types will return more or less data on dereference than I'd want. And I cast the pointer to the memory a lot
1 Reply
In what scenarios would deferencing return more or less data in a way that wouldn't work for you? It of course depends on the size of the type behind the pointer.
Casting the pointer itself to different types is fine, it's just copying the numeric value of the address while changing the declaring type. You just have to make sure that when the cast pointer is exposed, or dereferenced, it's at a location of an existing object of that type or a location where the next sizeof(T) bytes can be dedicated to such an object.
Span does specify a size so it's a bit safer in terms of staying in bounds compared to a raw pointer.