Cast pointer to generic structure

試著忘記壹切 提交于 2019-12-13 06:37:38

问题


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



来源:https://stackoverflow.com/questions/18166429/cast-pointer-to-generic-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!