I want to get a python app to pass a generic list to my C# code. I've created a demo app that duplicates the problem I'm seeing.
I have this python code (Python 2.7), MainApp.py, that calls a C# DLL (.NET 4.7):
import clr, sys
sys.path.append(r"C:\PathToMyProject\ClassLibrary1\bin\Debug")
clr.AddReference(r"C:\PathToMyProject\ClassLibrary1\bin\Debug\ClassLibrary1.dll")
from ClassLibrary1 import Class1
class Person:
def __init__(self, Name):
self.Name = Name
myclass = Class1()
nameList = []
nameList.append(Person("Joe"))
nameList.append(Person("Mary"))
nameList.append(Person("Chris"))
result = myclass.SayHello(nameList)
print(result)
Notice that I have a list of Person objects, nameList, that I'm trying to pass. Here's the C# code:
using System.Collections.Generic;
namespace ClassLibrary1
{
public class Class1
{
public string SayHello(List<dynamic> names)
{
return $"Hello, {names.Count} people!";
}
}
}
The SayHello method accepts a parameter of List<dynamic>. However, I receive the following error when running >python MainApp.py:
Traceback (most recent call last): File ".\MainApp.py", line 20, in result = myclass.SayHello(nameList) TypeError: No method matches given arguments for SayHello: (<type 'list'>)
I solved it with the following code:
MainApp.py:
Class1.cs:
The first thing I did was change the
SayHelloparameter type fromList<dynamic>todynamic[].That fixed the type error, but I began receiving a new message:
Apparently IronPython didn't let me pass custom types from python to C#. To fix this, I added a
Personclass to the C# code:Then I removed the custom Person class from the python code and referenced the one in the C# code:
Everything worked fine after that.