Proposal: UnsafeHelper class with IL-only As___() methods
See this issue I filed here: https://github.com/dotnet/runtime/issues/62342
tl;dr this method would be highly useful, but it's unclear whether it will be approved and added to .NET itself. So, why not put an implementation here in the toolkit?
As for its implementation, it cannot be done in C#. It would have to be via InlineIL.Fody https://github.com/ltrzesniewski/InlineIL.Fody , or as a post-build event that runs a little program using Mono.Cecil to rewrite the IL (all 2 instructions of it!) of the relevant methods.
namespace System.Runtime.CompilerServices
{
public static class Unsafe
{
// This name was chosen in part so it does not sort next to other methods like AsRef,
// therefore less probability it could be accidentally used (via auto-complete or etc.).
// sizeof(U) must equal sizeof(T*)
public static ref U AsPtrRef<T, U>(ref T* source)
where T : unmanaged
where U : unmanaged
// The inverse operation is needed as well, to convert from ref U back to ref T*
public static ref U* AsPtrRef<T, U>(ref T source)
where T : unmanaged
where U : unmanaged
// Might want to have `ref T**` versions as well, up to a reasonable arity. `ref T***` perhaps, but `ref T*******` is a bit much. `T***` does _very occasionally_ pop up in native interop code (pointer to 2-dimensional array).
}
}
@Sergio0694 will probably have a better name for this methods :)
I've published a NuGet package that does this, so maybe this isn't needed in the CommunityToolkit. https://github.com/rickbrew/PointerToolkit/