Using Python Functions from CSharp
From IronPython Cookbook
The following example (adapted from code posted to the IronPython Mailing list by Dino Viehland), creates a Python function from code. That function is then used from C#.
It uses the IronPython 2 hosting API.
using System;
using Microsoft.Scripting;
using IronPython.Hosting;
namespace IP2Hosting
{
class Program
{
static void Main()
{
PythonEngine pe = PythonEngine.CurrentEngine;
string code = "lambda x, y: x > y";
Function<object, object, bool> func = pe.EvaluateAs<Function<object, object, bool>>(code);
// Writes False to the console
bool result = func(2, 3);
Console.WriteLine(result.ToString());
// Writes True to the console
result = func(3, 2);
Console.WriteLine(result.ToString());
}
}
}
You can also do the same thing from within IronPython. As you can only have one IronPython engine active at a time with IronPython 2, this isn't directly useful - *but* it does allow you to experiment with the API from the interactive interpreter which can be very useful.
import clr
clr.AddReference('Microsoft.Scripting')
clr.AddReference('IronPython')
from IronPython.Hosting import PythonEngine
from Microsoft.Scripting.Utils import Function
pe = PythonEngine.CurrentEngine
f = pe.EvaluateAs[Function[object, object, bool]]('lambda x, y: x > y')
f(2, 3)
f(3, 2)
Back to Contents.

