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

时间:2019-06-27 17:31:32

标签: c# python delegates python.net

我无法将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]]'

我该如何处理?

0 个答案:

没有答案