-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?

Clifford
  • 88,407
  • 13
  • 85
  • 165
Riscy
  • 843
  • 4
  • 13
  • 28
  • see http://stackoverflow.com/questions/5209675/passing-lists-from-ironpython-to-c-sharp ... first google hit for your exception ... looks like exactly your issue – Simon Opelt May 18 '12 at 06:13
  • I have google this and it hard to fine results! but thank anyway. – Riscy May 18 '12 at 16:57
  • Beside this is NET2, I was asking about NET4 which may have different methodology. – Riscy May 18 '12 at 16:59

1 Answers1

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);
Simon Opelt
  • 6,136
  • 2
  • 35
  • 66