ILSpy icon indicating copy to clipboard operation
ILSpy copied to clipboard

Cannot declare a pointer to a managed type 'T'

Open marwie opened this issue 4 years ago • 1 comments

Input code

Please see https://github.com/icsharpcode/ILSpy/issues/2389

Unfortunately I cant find it in CSReference

Erroneous output

private unsafe static void InternalCopyPtrToStructure<T>(void* ptr, out T output) where T : struct
{
      //   <UnityEngine>\Unity\Collections\LowLevel\Unsafe\UnsafeUtility.cs:11651 Cannot declare a pointer to a managed type 'T'
	output = *(T*)ptr;
}
public unsafe static void* AddressOf<T>(ref T output) where T : struct
{
        //   <UnityEngine>\Unity\Collections\LowLevel\Unsafe\UnsafeUtility.cs:11197 Cannot resolve symbol 'Unsafe'
	return System.Runtime.CompilerServices.Unsafe.AsPointer(ref output); 
}
public unsafe static int SizeOf<T>() where T : struct
{
       //   <UnityEngine>\Unity\Collections\LowLevel\Unsafe\UnsafeUtility.cs:11302 Cannot take the size of a variable of a managed type 'T'
	return sizeof(T);
}

image image image

Details

I'm not sure if this is actually wrong or just a configuration problem. Here is what Rider decompiler produces for example for the same types

private static unsafe void InternalCopyPtrToStructure<T>(void* ptr, out T output) where T : struct => output = *(T*) ptr;

public static unsafe void* AddressOf<T>(ref T output) where T : struct => (void*) ref output;

public static int SizeOf<T>() where T : struct => sizeof (T);

Please also see https://github.com/icsharpcode/ILSpy/issues/2389

marwie avatar May 05 '21 09:05 marwie

This is IL code that cannot be represented in C#.

For the AddressOf the decompiler detected this and instead generated a call to Unsafe.AsPointer. The other cases also have functions in System.Runtime.CompilerServices.Unsafe, but the decompiler can't yet detect whether the transformation to such a call would be necessary (we currently don't have logic to detect whether a type is managed).

dgrunwald avatar May 05 '21 19:05 dgrunwald

Sizeof was fixed back in 48a8351e27fad3d1c399efa1121cd066c54a4081. I've just fixed InternalCopyPtrToStructure by using Unsafe.Read to avoid the pointer-to-managed.

dgrunwald avatar Aug 11 '23 16:08 dgrunwald