.NET Inside Out Part 9 — Generating Func from a bunch of bytes in C# revisited

This is the ninth part of the .NET Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 – Virtual and non-virtual calls in C#

We know how to generate delegate from a byte array. Last time we did it by modifying some code using jumps here and there. Today we are going to use GetDelegateForFunctionPointer method.

Most important difference is in method generating the delegate:

Instead of modifying the machine code we just generate the pointer using .NET methods. We have our delegate but this doesn’t support generics, so we need the following:

This is just for type safety so we can pass correct parameters.

Our first test method looks like this:

You can see that we use dummy parameters just to adhere to the calling convention but generally this works correctly. Also notice, that the method is static, that’s because we don’t pass any instance.

Second test looks like this:

Last time we were accessing parameters through registers, this time they are passed via stack because there are additional delegate parameters which we don’t need. We also don’t build the method frame so we use esp register.

And we are done. Tested with .NET Framework 4.5 and Windows 10 x64 Enterprise compiled as AnyCPU and executed as x86.