Embedding IronPython - C# Calling Python Script Part 1
Friday, 8 June 2007
Embedding IronPython is quite trivial and is documented here.
You can call functions in the embedded python module by
(1) retrieving the function using Evaluate()
(2) then apply the function using the Call() method
using (IronPython.Hosting.PythonEngine engine
= new IronPython.Hosting.PythonEngine())
{
engine.Execute(@"
def foo(a, b):
return a+b*2");
// (1) Retrieve the function
IronPython.Runtime.Calls.ICallable foo
= (IronPython.Runtime.Calls.ICallable) engine.Evaluate("foo");
// (2) Apply function
object result = foo.Call(3, 25);
}
The ICallable.Call method can only be called varargs-style, and can’t be called using keyword arguments.
(This is probably a bug.)
Call(params object[] args)
To use keyword arguments, you’ll need to cast the function into PythonFunction.
Note:
Unfortunately, Python classes aren’t CLR classes, and couldn’t be accessed directly or subclassed by C# by referencing a built assembly. You’ll have to go through the hosting interfaces to get an instance of the class.
No. 1 — June 4th, 2008 at 3:53 am
Simple and informative, thank you!