2

How to parse C# source code for generating IL opcodes, that could be used in DynamicMethod?

I want to execute code dynamically without generating unnecessary assemblies. Something like this:

var body = "return \"sample\";";
var dm = new DynamicMethod("method_" + Guid.NewGuid().ToString("N"), typeof(string), null);
var parser = new SomeKindOfCSharpParser();
parser.Emit(body, m.GetILGenerator());
lorond
  • 3,856
  • 2
  • 37
  • 52
  • Are you using C# 5? If so, you're all set. If not, can you use Mono? – Gabe Jun 04 '12 at 12:28
  • 3
    Also, depending on *how* strict you need, you might be able to get away with CSharpCodeProvider with GenerateInMemory = false – Marc Gravell Jun 04 '12 at 12:30
  • @Gabe C# 4. I can use Mono. I found nice project NRefactory however i still need to implement Emit logic by my own. I didn't worked with Mono before. I'm missing something? – lorond Jun 04 '12 at 12:36
  • @MarcGravell With CSharpCodeProvider it required to build some more code around my statements. Also it's still generate assemblies even with `GenerateInMemory = false` and I need either to load them or extract bytecode, parse and emit. Isn't it? – lorond Jun 04 '12 at 12:41
  • @MarcGravell Moreover I'm forced to execute code in current domain. Number of loaded assemblies will grow too fast. – lorond Jun 04 '12 at 14:03
  • @Gabe What exactly do you mean? If you mean Roslyn, then that's not part of C# 5 or Visual Studio 2012, it should be included the the version following that (VS 2014?). – svick Jun 04 '12 at 15:20
  • @svick: Oops, you're right. I misthought. – Gabe Jun 04 '12 at 16:02

2 Answers2

1

There is no way to implement it.

You have a few ways to implement it:

  1. You can use C# compiler, but it will compile external cs file into separate assemby.
  2. You can use CodeDOM to build and compile code tree
  3. You can build Expression tree and compile it
  4. You can generate code one IL instruction after another
Viacheslav Smityukh
  • 5,652
  • 4
  • 24
  • 42
1

Roslyn should be something close to this...

TDaver
  • 7,164
  • 5
  • 47
  • 94