-1

I have the python code, which is saved into test.py

def Process():
   list1 = [1, 2, 3]                       #list object                    
   return list1

I also have C# code

        List<int> list1 = new List<int>(new int[3]);
        var runtime = Python.CreateRuntime();
        dynamic test = runtime.UseFile(m_sFilename);
        var list2 = test.Process();
        list1 = (List<int>)list2;           << Error
        /*
        list1[0] = list2[0];  // this code works fine but need how to
        list1[1] = list2[1];
        list1[2] = list2[2];
        */

When I run this I get RuntimeBinderException was unhandled

Cannot convert type 'IronPython.Runtime.List' to 'System.Collections.Generic.List'

How to fix this?

Also how to pass the list into the Python?

3
  • see stackoverflow.com/questions/5209675/… ... first google hit for your exception ... looks like exactly your issue Commented May 18, 2012 at 6:13
  • I have google this and it hard to fine results! but thank anyway. Commented May 18, 2012 at 16:57
  • Beside this is NET2, I was asking about NET4 which may have different methodology. Commented May 18, 2012 at 16:59

1 Answer 1

1

There are two ways to approaching this:

  1. Keep the python "vanilla" (free of .net/IronPython specific code, may be a requirement):

This gives you the following python script:

def Process(list):
    list1 = [1, 2, 3] #list object
    return list1 + list # concatenate lists

and C# code (Note how you can cast to IList<object> and then just use LINQ for further processing in .net. Depending on the amount of data/use-case you might also just keep using the IList returned by the IronPython runtime.):

var m_sFilename = "test.py";
var list = new IronPython.Runtime.List();
list.append(4);
list.append(5);
list.append(6);

var runtime = Python.CreateRuntime();
dynamic test = runtime.UseFile(m_sFilename);
var resultList = test.Process(list);

var dotNetList = ((IList<object>)resultList).Cast<int>().ToList();
  1. Use .net types in your interface/python code:

This would change your python code to:

import clr
clr.AddReference("System.Core")
import System
clr.ImportExtensions(System.Linq)
from System.Collections.Generic import List

def ProcessDotNetStyle(list):
    list1 = List[int]([1, 2, 3])
    return list1.Union(list).ToList()

and your C# would look like

var dotNetList = new List<int>(new[] { 4, 5, 6 });
dotNetList = test.ProcessDotNetStyle(dotNetList);
Sign up to request clarification or add additional context in comments.

2 Comments

How to do this for dictionary?
Have a look at IronPython.Runtime.PythonDictionary

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.