Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

passing Lists from IronPython to C#

I want to pass a list of strings from IronPython 2.6 for .NET 2.0 to a C# program (I'm using .NET 2.0 because I'm working with an api that runs off of DLLs built on 2.0). But I'm not sure how to cast it as it comes back from the ScriptEngine.

namespace test1
{
    class Program
    {
        static void Main(string[] args)
        {
            ScriptEngine engine = Python.CreateEngine();
            ScriptSource source = engine.CreateScriptSourceFromFile("C:\File\Path\To\my\script.py");
            ScriptScope scope = engine.CreateScope();

            ObjectOperations op = engine.Operations;

            source.Execute(scope); // class object created
            object classObject = scope.GetVariable("MyClass"); // get the class object
            object instance = op.Invoke(classObject); // create the instance
            object method = op.GetMember(instance, "myMethod"); // get a method
            List<string> result = (List<string>)op.Invoke(method); // call the method and get result
            Console.WriteLine(result.ToString());
            Console.Read();
        }
    }
}

my python code has a class with a method that returns a python list of strings:

class MyClass(object):
    def myMethod(self):
        return ['a','list','of','strings']

I get this error:

Unable to cast object of type 'IronPython.Runtime.List' to type 'System.Collections.Generic.List`1[System.String]'.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IronPython.Runtime.List implements the following interfaces:

IList, ICollection, IList<object>, ICollection<object>, IEnumerable<object>, IEnumerable

so you can cast to one of this types an then turn into a List<string>.

List<string> result = ((IList<object>)op.Invoke(method)).Cast<string>().ToList();

BTW, maybe you are aware of it, but you can also use .NET types in IronPython e.g.:

from System.Collections.Generic import *

class MyClass(object):
    def myMethod(self):
        return List[str](['a','list','of','strings'])

here myMethod returns directly a List<string>


EDIT:

Given that you're using .net 2.0 (so no LINQ) you have two options (IMO):

1. Cast to IList<object> and use it:

IList<object> result = (IList<object>)op.Invoke(method);

PROs: no loop required, you will use the same object instance returned by the python script.
CONs: no type safety (you will be like in python, so you can add also a non-string to the list)

2. Convert to a List<string>/IList<string> :

IList<object> originalResult = (IList<object>)op.Invoke(method);
List<string> typeSafeResult = new List<string>();
foreach(object element in originalResult)
{
    typeSafeResult.Add((string)element);
}

PROs: type safe list (you can add only strings).
CONs: it requires a loop, and the converted list is a new instance (not the same returned by the script)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...