Embedding IronPython in C#

11,211

Solution 1

See embedding on the Voidspace site.

An example there, The IronPython Calculator and the Evaluator works over a simple python expression evaluator called from a C# program.

public string calculate(string input)
{
    try
    {
        ScriptSource source =
            engine.CreateScriptSourceFromString(input,
                SourceCodeKind.Expression);

        object result = source.Execute(scope);
        return result.ToString();
    }
    catch (Exception ex)
    {
        return "Error";
    }
}

Solution 2

You can try use the following code,

ScriptSource script;
script = eng.CreateScriptSourceFromFile(path);
CompiledCode code = script.Compile();
ScriptScope scope = engine.CreateScope();
code.Execute(scope);

It's from this article.

Or, if you prefer to invoke a method you can use something like this,

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);
}

This example is from here.

Share:
11,211

Related videos on Youtube

Darren Young
Author by

Darren Young

Updated on May 31, 2022

Comments

  • Darren Young
    Darren Young about 2 years

    I am just looking into using IronPython with C# and cannot seem to find any great documentation for what I need. Basically I am trying to call methods from a .py file into a C# program.

    I have the following which opens the module:

    var ipy = Python.CreateRuntime();
    var test = ipy.UseFile("C:\\Users\\ktrg317\\Desktop\\Test.py");
    

    But, I am unsure from here how to get access to the method inside there. The example I have seen uses the dynamic keyword, however, at work I am only on C# 3.0.

    Thanks.