将现有方法附加到动态程序集而不是为其生成 IL [英] Attaching an existing method to a dynamic assembly instead of generating IL for it

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

问题描述

我是 Reflection.Emit API 的新手,并且生成了一个带有入口点的最小程序集,该入口点基于一些简单的 I/O 检查返回一个退出代码.创建外部程序集的原因是一段代码需要在当前进程空间之外运行,并且本身将是瞬态的.它最终会被创建的应用程序删除.

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.

话虽如此,要生成的代码相当复杂,我宁愿避免为瞬态程序集创建单独的项目.我不太了解 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 的this SO question,并且似乎不可能缺少解析伊利诺伊州.我不知道采用现有方法的方法,将其与当前上下文分离并将其添加到新的动态类型.如果存在这种方式,那将是这篇帖子的可接受答案.

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?

推荐答案

最终使用表达式树解决了这个问题,而不必发出原始 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 进行微性能的情况.

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

这篇关于将现有方法附加到动态程序集而不是为其生成 IL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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