4

I can't subscribe my python function to a delegate method inside a .dll lib file written in c# net.

This lib is written to communicate with a device. I successfully import the lib via pythonnet. I can use some methods of the lib like sending commands, getting basic information about the device etc.

In Visual Studio the definition of the delegate method in the object browser is like this:

public : System::EventHandler<LibOfMyDevice::BasicInfo^>^ BasicInfoChanged
Member of LibOfMyDevice::OneDevice

In a C example I can subscribe like this:

Device.BasicInfoChanged += BasicInfoChanged;
...
private void BasicInfoChanged(object sender, BasicInfo info) {
    if (InvokeRequired)
        Invoke(new Action<BasicInfo>(HandleBasicInfoChanged), info);
    else
        HandleBasicInfoChanged(info);
    }
...
private void HandleBasicInfoChanged(BasicInfo info) {
    switch (info.Status) {
        // do something
    }
}

In a C++ example I can subscribe like this:

device->BasicInfoChanged += gcnew EventHandler<LibOfMyDevice::BasicInfo^>(this, &MyForm::BasicInfoChanged);
...
void BasicInfoChanged(System::Object^ sender, LibOfMyDevice::BasicInfo^ info) {
    if (info->Status== LibOfMyDevice::BasicInfo::Status::Connected) { 
        // do something         
    }
}

So far I tried these in python without success:

import clr
...
def my_python_handler(sender, info):
    print(sender, info)


# try 1)
# eventHandler = getattr(System, 'EventHandler`1')
# dc = EventHandler[BasicInfo](my_python_handler)
# device.BasicInfoChanged += dc
#
# >>> TypeError: unsupported operand type(s) for +=: 'NoneType' and '0, Culture=neutral, PublicKeyToken=null]]'

# try 2)
# action = getattr(System, "Action`1")
# dc = Action[BasicInfo](my_python_handler)
# device.BasicInfoChanged += dc
# 
# >>> TypeError: unsupported operand type(s) for +=: 'NoneType' and '0, Culture=neutral, PublicKeyToken=null]]'

# try 3)
# device.BasicInfoChanged += EventHandler[BasicInfo](Action[str](my_python_handler))
#
# >>> TypeError: unsupported operand type(s) for +=: 'NoneType' and '0, Culture=neutral, PublicKeyToken=null]]'

# try 4)
# iuc = EventHandler[EventArgs](my_python_handler)
# device.BasicInfoChanged += iuc
#
# >>> TypeError: unsupported operand type(s) for +=: 'NoneType' and '0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'

# try 5)
# eventhandler = EventHandler[BasicInfo](my_python_handler)
# device.BasicInfoChanged += eventhandler
#
# >>> TypeError: unsupported operand type(s) for +=: 'NoneType' and '0, Culture=neutral, PublicKeyToken=null]]'

# try 6)
# device.BasicInfoChanged += Action[str](my_python_handler)
#
# >>> TypeError: unsupported operand type(s) for +=: 'NoneType' and '0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'

How do I need to approach this?

cquests
  • 41
  • 2

0 Answers0