Why does this code throw "System.Security.VerificationException: Operation could destabilize the runtime."?
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);
The exception isn't thrown due to wrong arguments.
As far as I know, you cannot build Expression trees containing unsafe code. Unsafe code means that type/memory safety cannot be verified, but according to this error description Expressions can only be compiled if their code is verifiable.
It should be fine to just pass around IntPtr
in the expression tree but that wouldn't help if the argument is void*
.
A viable way might be using Reflection.Emit
to generate the method access IL directly. It cannot by default call a private method but here's an answer for solving that: https://stackoverflow.com/a/1778446/1659828
Anyway in your case I don't know what you're trying to accomplish, but trying to use an implementation detail of non-CLS-compliant API seems like there might be a better approach.