问题描述
我正在准备将指针投射到通用结构(可漂白).当我使用非通用结构时,一切似乎都很好=>然后我可以使用Marshal.PtrToStructure(...),但是该函数无法接收通用结构(为什么?)
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 ?)
所以我写了以下内容:
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();
}
但是现在Ldobj指令有问题. VS给我:附加信息:操作可能会破坏运行时的稳定性.
But now it is something wrong with the Ldobj instruction. VS gives me:Additional information: Operation could destabilize the runtime.
我在做什么错?有谁知道解决这个问题的更好方法(通用结构的ptr)或发现此函数中的错误?
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?
推荐答案
我不确定这是否适用于通用指针,但是.net中有一种方法可以在类型之间进行低级转换.它涉及StructLayout属性和FieldOffset为0的多个字段.
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
这篇关于将指针转换为通用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!