November 24, 2009

Embedding IronPython Within C#

IronPython is a Python implementation that runs on the .Net DLR and allows the use of the powerful .Net Framework from Python. While this is very exciting for Python development, there are also great advantages for other .Net languages. Using IronPython, we can run Python code from without a .Net application. More specifically, we can allow a .Net application to be extendable or scriptable with python.

In the following example, I will create a basic python 'plugin' framework in C#.

Python Code
class TestClass(object):
def __init__(self):
self.A = 5
self.B = 4
def Go(self):
return self.A + self.B

C# Code
public static object Execute(string code)
object result;

ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
ScriptSource source = engine.CreateScriptSourceFromString(code);
object t = scope.GetVariable("TestClass");
object o = engine.Operations.CreateInstance(t);
object r = engine.Operations.InvokeMember(o, "Go");
result = r;
catch (Exception ex)
result = ex;

return result;