如何使用pythonnet将python函数订阅到C#.Net委托方法?(TypeError:不支持的操作数类型)

2024-04-23 04:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法将python函数订阅到用c#net编写的.dll lib文件中的委托方法。你知道吗

这个lib是用来与设备通信的。我通过pythonnet成功地导入了lib。我可以使用lib的一些方法,比如发送命令,获取设备的基本信息等等

在Visual Studio中,对象浏览器中委托方法的定义如下:

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

在C示例中,我可以这样订阅:

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
    }
}
在C++示例中,我可以订阅如下:

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         
    }
}

到目前为止,我在python中尝试了这些,但没有成功:

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]]'

我需要如何处理这个问题?你知道吗


Tags: andinfoformydevicetypehandlertry