'PythonNet: How to convert a Python defined class into a c# class when calling C# from Python?
I have a C# app which calls a Python method (Python 3.9.6), which internally calls back into my C# application.
The C# dll is being imported into python using from/import and is working fine.
There are 2 callbacks back into C#
1st : The python call passes an int: AppBind.SendInt(5)
and on the c# side, I get the int like this:
public void SendInt(PyObject o)
{
int x = (int)o.AsManagedObject(typeof(int));
}
That works fine.
2nd: The Python call passes in a Python defined and created class:
class ItemTest(object):
def __init__(self):
self.TestInt = 1
...
i = ItemTest()
i.TestInt = 123
AppBind.SendClass(i)
on the c# side, I have a companion class:
public class ItemTest
{
public int TestInt;
}
And have this code on C# side
public void SendClass(PyObject o)
{
ItemTest x = (ItemTest)o.AsManagedObject(typeof(ItemTest));
}
I just get the following error:
System.InvalidCastException: 'cannot convert object to target type'
This is where I am stuck.
If I try calls like this:
if (o.HasAttr("TestInt"))
{
PyObject v = o.GetAttr("TestInt");
}
then I get the following error: System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
EDIT: I've looked at IPyObjectDecoder and Codecs but saw that IPyObjectDecoder is deprecated, so I assume I shouldn't be using that
What is the correct way to convert the Python class to C#? Is manually decoding it the best way? Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
