I'm attempting to call a C# function from a Python script, via the clr
module from the PythonNet
library.
One of the arguments that this C# function takes is of the type System.Collections.Generic.IEnumerable
. Simply supplying a list of the required data types to the first argument results in a 'list' value cannot be converted to 'System.Collections.Generic.IEnumerable'
error.
After searching online, the supposed .NET datatypes should already be included in the Python installation, and I should be able to access them. However, I'm unsure as to how.
Doing:
from System.Collections.Generic import *
Fails because the module isn't found, while doing:
import collections
Doesn't have a namespace IEnumerable
.
How would I go about converting a Python list to the System.Collections.Generic.IEnumerable
data type?
Thanks for reading my post, any guidance is appreciated.
After messing around in the Python script for a few hours, I managed to figure out a solution:
First, the actual C# Collections
namespace has to be imported via the clr
module as such:
clr.AddReference("System.Collections")
Then, the specific data type of the Collections
namespace has to be imported:
from System.Collections.Generic import IEnumerable
And then one should be able to use the respective data type, and call all the class functions it has. In my case, I wanted to convert a Python List
into the IEnumerable
datatype. Therefore, I could iterate over my Python List
, and call the Add
function of the IEnumerable
class (using datatype of int
as an example):
myList = [1, 2, 3]
myIEnumerable = IEnumerable[int]()
for i in range(len(myList)):
myIEnumerable.Add(myList[i])
As a sidenote, while the C# function that I wanted to call from my Python script has one of its arguments listed as accepting a type of System.Collections.Generic.IEnumerable
, I managed to get it to work with having a System.Collections.Generic.List
type instead. Perhaps it'll be useful for someone else.