Calling Python from C#

Calling Python from C#

Follow the instructions:

  1. Install IronPython and get SymPy
  2. Add these resources to your project
    IronPython.dll
    IronPython.Modules.dll
    Microsoft.Dynamic.dll
    Microsoft.Scripting.dll
  3. C# code as follows:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;

namespace TestPy
{
    class Program
    {
        static void Main(string[] args)
        {
            var options = new Dictionary<string, object>();
            options["Frames"] = true;
            options["FullFrames"] = true;
            ScriptEngine engine = Python.CreateEngine(options);
            var paths = engine.GetSearchPaths();
            paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
            paths.Add(@"C:\dev\sympy\sympy-0.7.6"); //also the following is working
            //paths.Add(@"C:\python34_64bit\Lib\site-packages");
            engine.SetSearchPaths(paths);

            // expression to simplify
            var expr = "0 + 1 * 1 * (x - 2) / (1 - 2) * (x - 3) / (1 - 3) * (x - 4) / (1 - 4) + 8 * 1 * (x - 1) / (2 - 1) * (x - 3) / (2 - 3) * (x - 4) / (2 - 4) + 27 * 1 * (x - 1) / (3 - 1) * (x - 2) / (3 - 2) * (x - 4) / (3 - 4) + 64 * 1 * (x - 1) / (4 - 1) * (x - 2) / (4 - 2) * (x - 3) / (4 - 3)";

            string myexpr = Console.ReadLine();

            if (myexpr !=null && myexpr.Length>1)
            {
                expr = myexpr;
            }

            var scope = engine.CreateScope();

            var script = engine.CreateScriptSourceFromString(@"
import codecs
def my_unicode_escape_decode(x):
    return x
codecs.unicode_escape_decode = my_unicode_escape_decode

from sympy import *
import clr
from System import String

expr = simplify('" + expr + @"')
result = clr.Convert(expr, String)
");

            script.Execute(scope);
            Console.WriteLine(scope.GetVariable("result"));
        }
    }
}

See a test below
sympy
gamma

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s