Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What ways exists to generate MSIL from unmanaged code

I am trying to create a backend of my language for .NET platform. The front-end and interpreter written in Delphi. Unmanaged API just allows type definitions but no emiting of MSIL.

What ways exist to generate MSIL from unmanaged code? Without using Reflection.Emit and using ILasm to attain this? Thank you.

like image 873
Sergey Antonov Avatar asked Jul 11 '10 08:07

Sergey Antonov


2 Answers

Delphi's .NET code generator emits IL as bytecode directly into memory, much like x86 code generation, though with appropriate headers etc. That is, the code generator directly emits bytes, exception tables etc., corresponding to the encoded IL format. It doesn't do this with an API, but rather the old-fashioned way: write the code a byte at a time.

Later, Delphi's built-in linker works with IMetaDataEmit etc. to generate metadata, and IMetaDataEmit::SetRVA to tell the metadata where the code is going to be located in the executable. The metadata is copied out with IMetaDataEmit::SaveToMemory and then copied out into the PE that the linker has been building up, with the CLR header correspondingly patched to point to the metadata start.

It's a lot of code, some of it fiddly, as it's much of it is threaded through Delphi's existing x86 linker, which does things like branch optimization and elimination of unused code (smart linking) which strictly speaking isn't generally necessary for .NET.

If we were to do it all again, we might very well avoid the .NET APIs for creating metadata, and generate the whole thing straight from the spec. The APIs ended up being a black box for optimization, and added up to a substantial amount of compilation time.

like image 129
Barry Kelly Avatar answered Sep 20 '22 23:09

Barry Kelly


From unmanaged code? TBH, the best suggestion I have is either "use P/Invoke", or "figure out what it is meant to do, and re-implement it".

Even if you can find something to port the unmanaged code, and even if it works - it isn't exactly going to leverage the framework. And it isn't exactly 1:1 between unmanaged and managed.

like image 21
Marc Gravell Avatar answered Sep 21 '22 23:09

Marc Gravell