Skip to content

RuntimeBinderException - Cannot implicitly convert type 'Python.Runtime.PyObject' to 'System.Collections.Generic.List<string>' #451

Closed
@tomhunter-gh

Description

@tomhunter-gh

Environment

  • Pythonnet version: 2.3.0
  • Python version: 3.6 (Anaconda 32-bit)
  • Operating System: Windows 10

Details

I have the following code:

Interface1.cs

using System.Collections.Generic;

public interface Interface1
{
    string Test();

    List<string> GetList();

    List<MyType> GetListOfMyType();
}

public class MyType
{
}

Class1.cs

using System.Collections.Generic;

namespace Python.EmbeddingTest
{
    public class Class1 : Interface1
    {
        public string Test()
        {
            return "test";
        }

        public List<string> GetList()
        {
            return new List<string>() { "testing" };
        }

        public List<MyType> GetListOfMyType()
        {
            return new List<MyType>() { new MyType(), new MyType() };
        }
    }
}

Module1.py

import clr

clr.AddReference("Python.EmbeddingTest")
from Python.EmbeddingTest import *

class Class2(Class1):

    def Test(self):
        return "Test from Class2"
    
    def Method1(self):
        return "Method1"

Test

I am trying to do something like what the following test is trying to do:

[Test]
public void TestGenericListMarshalling()
{
    var scope = Py.Import("module1");
    var attr = scope.GetAttr("Class2");
    dynamic c2 = attr.Invoke();
    List<string> ls = c2.GetList();
}

Exception

However, I get the following exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException occurred
  HResult=0x80131500
  Message=Cannot implicitly convert type 'Python.Runtime.PyObject' to 'System.Collections.Generic.List<string>'
  Source=Python.EmbeddingTest
  StackTrace:
   at Python.EmbeddingTest.PyImportTest.TestGenericListMarshalling() in D:\Users\Tom\Dropbox\Algo Trading\pythonnet\src\embed_tests\pyimport.cs:line 90

Is it possible to marshall generic .NET Lists?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions