Why does LambdaExpression.Compile() work on iOS (Xamarin)?

南笙酒味 提交于 2019-12-04 17:07:04

问题


Since Xamarin.iOS doesn't support code generation at runtime, why do Compile() and DynamicInvoke() work as expected?

For example, the following code works fine:

var lambda = Expression.Lambda(
                          Expression.Add(
                              Expression.Constant(1),
                              Expression.Constant(2)
                          )
             );

var f = lambda.Compile();
var result = f.DynamicInvoke();

// result==3 at this point

Is Xamarin evaluating the expression tree at runtime instead of emitting IL code?


回答1:


On platforms that support code generation, Reflection.Emit-based LambdaCompiler is used.

If that's not available, the expression is interpreted using the interpreter. For example, there are classes that interpret Constant and Add.




回答2:


The details of the Xamarin limitations are here.

You don't seem to be using anything in the Reflection.Emit namespace, which is the big no-no. Your code must still be AOT'd. Otherwise, I would imagine it would not work.

But there HAVE been examples of [native] developers thwarting the iOS static analysis tool and circumventing the dynamic code restriction. I tried to locate the article, but couldn't find it.

Anyway, I don't think your scenario exemplifies that. Your code example will still be AOT-compiled.

But you raise a really good question: at what time does the expression get evaluated?

EDIT:

Another SO answer on the same topic: What does Expression.Compile do on Monotouch?

There's also some good info on Expression.Compile() and "full AOT" here: http://www.mono-project.com/docs/advanced/aot/

EDIT: After reading some more, I think I know what's going on here. It's not that Expression.Compile() won't work...it's that when your iOS app bundle is subjected to the iOS static analysis tool when you submit it to the app store, it will not pass the analysis, because it is dynamically generating code. So, sure, you can use Expression.Compile(), but don't expect it to be accepted into the app store. But as mentioned by @svick, if you use the "full AOT" compile option, your Expression.Compile() will probably fail at runtime, or perhaps even fail compilation.



来源:https://stackoverflow.com/questions/29245589/why-does-lambdaexpression-compile-work-on-ios-xamarin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!