pythonnet icon indicating copy to clipboard operation
pythonnet copied to clipboard

Cannot convert to managed type

Open Tiehong opened this issue 3 years ago • 2 comments

Environment

  • Pythonnet version: 3.0.0-rc4
  • Python version: 3.8
  • Operating System: Windows11
  • .NET Runtime: .NET Framework 4.8

Details

With the following code in C#, when a Python class has getitem() defined, it will be converted to an array (System.Object[]) in managed code:

List lst = new List(); using (Py.GIL()) { using (var scope = Py.CreateScope()) { scope.Set("lst", lst); string text = @" class DBRow: def init(self, row, col_names): self.row = row self.col_names = col_names

def __getitem__(self, key):   
    if isinstance(key, int):
        return self.row[key]

    if key in self.col_names:
        index = self.col_names.index(key)
        return self.row[index]
    else:
        return None 
        

col_names=['col1', 'col2', 'col3'] row=[1, '2', 3]

r = DBRow(row, col_names) lst.Add(r) ";

                    var code = PythonEngine.Compile(text);
                    scope.Execute(code);
                }
            }
            string str = lst[0].GetType().ToString();

Tiehong avatar Aug 08 '22 18:08 Tiehong

Can you clarify? The bug is that str variable ends up being System.Object[], and you expect it to be PyObject?

lostmsu avatar Aug 08 '22 19:08 lostmsu

Yes, @lostmsu. I expect it to be PyObject. Then I can view the class members/properties in the C# world. System.Object[] does not allow me to do that.

Tiehong avatar Aug 09 '22 16:08 Tiehong

I believe this should be fixed now.

lostmsu avatar Sep 16 '22 23:09 lostmsu