Cast pointer to generic structure

2019-09-07 15:06发布

问题:

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?

回答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