In C# you're not suppose to be able to create pointer to managed types but with this API you are able to, using Unsafe.AsPointer<T>
.
https://www.nuget.org/packages/System.Runtime.CompilerServices.Unsafe/
I see the source code using ILSpy and I saw this:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.Versioning.NonVersionable]
public unsafe static void* AsPointer<T>(ref T value)
{
return &value;
}
Also in other similar API:
//Unity.Collections.LowLevel.Unsafe.UnsafeUtility
public unsafe static T ReadArrayElement<T>(void* source, int index)
{
return *(T*)((byte*)source + index * sizeof(T));
}
How this works and how is possible to replicate that behaviour?
The code in question is not valid C# code and was probably not written in C# in the first place. What you see is ILSpy's C# representation of the underlying code - the C# syntax is capable of representing this because it's just a compiler rule that says you can't get a pointer to a managed type.
My guess (I don't know this for a fact) that the code in question was written in IL in the first place - if you decompile it to IL, you can see that it's a trivial bit:
.method public hidebysig static
void* AsPointer<T> (
!!T& 'value'
) cil managed flag(0100)
{
.custom instance void
System.Runtime.Versioning.NonVersionableAttribute::.ctor() = (
01 00 00 00
)
// Method begins at RVA 0x2190
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u
IL_0002: ret
} // end of method Unsafe::AsPointer
(This is from System.Runtime.CompilerServices.Unsafe.dll.)
The managed instance is loaded onto the stack and then it's simply returned as an unsigned pointer value.
If you want to recreate this behavior, you can - simply write your DLL in IL and compile it, then reference it from any other .NET language that supports pointers.