Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LambdaExpression.CompileToMethod not working with System.Type?

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));
    }
like image 927
Mihai Avatar asked Sep 08 '26 05:09

Mihai


1 Answers

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.

like image 64
Stephen McDaniel Avatar answered Sep 09 '26 19:09

Stephen McDaniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!