I am trying to make a programming language. The problem occurs when trying compile lambda into a module, more precisely when trying to convert from string to t(some type) using Convert.ChangeType instead of t.Parse. If I use LambdaExpression.Compile and using DynamicInvoke on the delegate it works, but if I use CompileToMethod and generate a module(abc.exe) and convert using Convert.ChangeType it throws an exception when I run the module: System.TypeAccessException was unhandled Message=Attempt by method 'Foo.Main()' to access type 'System.RuntimeType' failed.
Method used to convert:
private static Expression ConvertExpression<T>(Expression exprToConvert)
{
Type[] types = new Type[] { typeof(object), typeof(Type) };
MethodInfo changeTypeMethod = typeof(System.Convert).GetMethod("ChangeType", types);
Expression convertedExprAsObject = Expression.Call(changeTypeMethod, exprToConvert, Expression.Constant(typeof(T)));
return Expression.Convert(convertedExprAsObject, typeof(T));
}
I was able to reproduce the exception you got (that was the hardest part :-)). Then I was able to see if changing the following code made a difference:
Expression.Constant(typeof(T))
to:
Expression.Constant(typeof(T), typeof(Type))
With just that one small change it all seemed to work correctly. Creating the Constant as being of type Type makes everything happy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With