Question

Basically I have two questions:

1) How to emit or generate a IronPython code (tools, libs) in a C# application. The result of this process should be string consisting of real IronPython code not IL code.

2) How beneficial is the approach above over generating a IronPython code on your own (simply by using StringBuilder)?

I am looking for some code generator library similar to this IMAGINARY pseudo code generator:

IronPythonCodeGenerator generator = new IronPythonCodeGenerator();
Parameter param = new Parameter("str");
ParameterValue value=new ParameterValue(param,"This piece is printed by the generated code!!!");
Function function = IronPythonCodeGenerator.CreateFunction("PrintExtended",param);
function.AppendStatement("print",param);
function.AppendStatement(Statements.Return);
FunctionCall functionCall = new FunctionCall(function,value);
generator.MainBody.Append(function);
generator.MainBody.Append(functionCall);

Console.WriteLine(generator.MainBody.ToString());

, which outputs the IronPython code:

def PrintExtended( str ):
   print str;
   return;

PrintExtended("This piece is printed by the generated code!!!");
Était-ce utile?

La solution

Reflection.Emit is for generating IL code, not for generating high-level language code. So if your target language is IronPython, building it up in a StringBuilder is probably your best bet.

It of course depends on your needs. If all you want to do is just generate code without wanting to change the order of methods, or modify methods after they've been defined etc., just constructing code in a StringBuilder and then compiling it would be the easiest way.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top