附加现有的方法来动态组装,而不是产生IL吧 [英] Attaching an existing method to a dynamic assembly instead of generating IL for it

查看:126
本文介绍了附加现有的方法来动态组装,而不是产生IL吧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的 Reflection.Emit的 API,并产生与返回基于一些简单的我退出code切入点最低限度组件/ O检查。其原因创建外部组件是一块code需要当前进程空间外运行,将瞬态本身。它最终将被创建的应用程序被删除。

I am new to the Reflection.Emit API and have generated a bare minimum assembly with an entry point that returns an exit code based on a few simple I/O checks. The reason for creating an external assembly is that a piece of code needs to run outside the current process space and will be transient itself. It will eventually be deleted by the creating app.

说了这么多,在code可生成相当复杂,我宁愿避免创造一个短暂的装配一个单独的项目。我不知道IL不够用的ILGenerator这种复杂的方法。

Having said that, the code to be generated is quite complex and I would rather avoid creating a separate project for a transient assembly. I don't know IL enough to use the ILGenerator for this complex a method.

我也看过此等问题如何利用现有的方法来生成白细胞介素,它似乎并不可能短期解析IL。我不知道的方式来利用现有的方法,从目前的情况下分离,并把它添加到新的动态类型。如果这样的方式存在,这将是一个可以接受的答案,这个帖子。

I have also read this SO question about using existing methods to generate IL and it does not seem possible short of parsing IL. I don't know of a way to take an existing method, detach it from the current context and add it to the new dynamic type. If such a way exists, that would be an acceptable answer to this post.

我最后虽然是已经生成的程序集引用发生组件作为库。即使这两个组件是的WinForms应用程序,有一个缺点引用它们作为一个库?

My final though is to have the generated assembly reference the generating assembly as a library. even though both assemblies are WinForms apps, is there a downside to referencing them as a library?

推荐答案

使用防爆pression树,而不必发出生IL最后解决了这个问题。

Finally solved it using Expression Trees instead of having to emit raw IL.

var queue = new Queue<Expression>();
var arguments = Expression.Parameter(typeof(string []), "args");

queue.Enqueue(Expression.Call(typeof(Console).GetMethod("WriteLine", new Type [] { })));

var block = Expression.Block(queue);
var lambda = Expression.Lambda<Func<string [], int>>(block, new ParameterExpression [] { arguments });

lambda.CompileToMethod(builderMethod);
// builderMethod is a MethodBuilder instance created earlier.

这是非常强大的功能,绝对适合在不使用的ILGenerator要求微PERF的情况。

This is very powerful indeed and definitely suited for situations where micro-perf is not required using ILGenerator.

这篇关于附加现有的方法来动态组装,而不是产生IL吧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆