0

I am traying to cast a pointer to a generic structure (blittable). It all seems fine when I am doing with non-generic structures => then I am able to use Marshal.PtrToStructure(...) but that function does not receive generic structures (Why ?)

So I wrote the following:

public static object ReadValue<T>(IntPtr ptr) where T : struct
    {
        var dm = new DynamicMethod("$", typeof(T), Type.EmptyTypes);
            ILGenerator il = dm.GetILGenerator();
            il.Emit(OpCodes.Ldc_I4, ptr.ToInt32());
            il.Emit(OpCodes.Ldobj, typeof(T));
            il.Emit(OpCodes.Ret);

            var func = (Func<T>)dm.CreateDelegate(typeof(Func<T>));
            return func();
    }

But now it is something wrong with the Ldobj instruction. VS gives me: Additional information: Operation could destabilize the runtime.

What am I doing wrong ? Does anyone knows better approach to this problem (ptr to generic structure) or has spotted an error in this function?

dajuric
  • 2,373
  • 2
  • 20
  • 43

1 Answers1

1

I am not sure if this works with generic pointers but there is a way in .net to low level cast between types. It involves the StructLayout attribute and multiple fields at FieldOffset of 0.

http://netpl.blogspot.com/2010/10/is-net-type-safe.html

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • Thank you. I did not remember that. But unfortunately to good to be true: Could not load type 'PointerToStructure`1' from assembly 'ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because generic types cannot have explicit layout. – dajuric Aug 10 '13 at 21:39
  • You could forget generics, pass it as an object and cast back in the caller. – Wiktor Zychla Aug 10 '13 at 21:45
  • I tried with an interface and it gives me an error (addresses cannot be overlapped...) . I can not use object because an object does not have specific size (if you mean for the FieldOffset(0)] – dajuric Aug 10 '13 at 21:48