LINQ表达式抛出VerificationException

时间:2014-12-13 20:09:37

标签: c# clr linq-expressions

为什么这段代码会抛出“ System.Security.VerificationException:操作可能会破坏运行时的稳定性。”?

MethodInfo mi = typeof(TypedReference).GetMethod("InternalMakeTypedReference", BindingFlags.NonPublic | BindingFlags.Static);
ParameterExpression p1 = Expression.Parameter(typeof(IntPtr));
ParameterExpression p2 = Expression.Parameter(typeof(object));
ParameterExpression p3 = Expression.Parameter(typeof(IntPtr[]));
ParameterExpression p4 = Expression.Parameter(typeof(Type));
Expression exp = Expression.Call(mi, Expression.Convert(p1, typeof(void*)), p2, p3, Expression.Convert(p4, Types.RuntimeType));
var m = Expression.Lambda<Action<IntPtr,object,IntPtr[],Type>>(exp, p1, p2, p3, p4).Compile();
m(IntPtr.Zero,null,null,null);

由于错误的参数,不会引发异常。

1 个答案:

答案 0 :(得分:1)

据我所知,您无法构建包含不安全代码的表达式树。不安全的代码意味着无法验证类型/内存安全性,但根据this error description表达式只有在其代码可验证时才能编译。

只需在表达式树中传递IntPtr即可,但如果参数为void*则无效。

一种可行的方法可能是使用Reflection.Emit直接生成方法访问IL。它不能默认调用私有方法,但这是解决问题的答案:https://stackoverflow.com/a/1778446/1659828

无论如何,在你的情况下,我不知道你想要完成什么,但是尝试使用非CLS兼容API的实现细节似乎可能有更好的方法。