Search code examples
pythonc#clrpython.net

Using C# DLL in Python3 with Pythonnet


I'm using c# dll in Python3, and the module I'm using is DaveSkender/Stock.Indicators It is written in C# and complies with the Common Language Specification (CLS). So I compiled it as dll and imported in Python3 like below:

import clr
clr.AddReference(r'dll/Skender.Stock.Indicators')

Until now, It works and can be sure that module imported successfully. But the problem is passing parameter. There is a method like this in C# DLL:

public static IEnumerable<SmaResult> GetSma<TQuote>(
            IEnumerable<TQuote> history,
            int lookbackPeriod)
            where TQuote : IQuote
        {
            // WHATEVER
        }

So I passed the params in Python like this:

from System.Collections.Generic import List

// Definitely, Qoute is inherited from IQoute 
history_list = List[Qoute]()
Indicator.GetSma(history_list, int(1))

But it keeps showing TypeError:

TypeError: No method matches given arguments for GetSma: (<class 'System.Collections.Generic.0, Culture=neutral, PublicKeyToken=null]]'>, <class 'int'>)

I don't know which type in Python is compatible with C#. What should I pass in this method? I mean what should I pass for IEnumerable in Python?


Solution

  • Thank to @Ralf, I looked inside C# code again about GetSma(). And it is Generic method, should be called in Generic form. So I tried to call this method like the below:

    Indicator.GetSma[Qoute](history_list, int(1))
    

    It works!! Hope this answer to be helpful if there is someone like me.