.NET 4.5 MethodBuilder.SetMethodBody

﹥>﹥吖頭↗ 提交于 2019-12-04 10:02:12
aboveyou00

The real answer to my question was posted as a comment, instead of an answer, so in case anybody else ever has this question... here's the posted answer:

You'll need the SignatureHelper class. Fixups are only for compilers that translate native code to IL, like C++/CLI. – Hans Passant Mar 10 at 13:02

So... in order to get the byte array for the local signatures, you can execute this code:

var sig = SignatureHelper.GetLocalVarSigHelper(this.module);
sig.AddArgument(typeof(int)); //Local #0 is of type int
...
sig.AddArgument(typeof(string)); //Local #n is of type string
var sigArray = sig.GetSignature();

And in order to set the method body on the MethodBuilder, you call

MethodBuilder.SetMethodBody(il, maxStack, sigArray, handlers, fixups);

...where il is a byte[] with valid IL instructions (see this page), maxStack is an integer with the number of spots to reserve on the stack for the method, handlers is an System.Reflection.Emit.ExceptionHandler[], and fixups is a int[] array that can be ignored (with one exception, see below.)

One thing that I disagree with in Hans Passant's comment is that fixups are not only for compilers that translate native code into IL. I discovered when working on this that if you try to emit a call to a MethodBuilder method, it emits the wrong instruction. Looking at ILGenerator in .NET reflector, I found out that they emit a fixup each time they emit a method call. Adding a fixup for each method call indeed fixed this problem. There may be other places where you need to emit a fixup for it to work correctly, but I haven't looked into it much.

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