Pythonnet中泛型委托方法未被调用

3
我正在使用Python脚本和Pythonnet驱动C#库。该库在某些事件上触发委托方法。我注册了委托方法,但它没有被调用。
所涉及的方法定义为event EventHandler<EventArgs> SystemInformationUpdated 有趣的是,另一个具有自定义类返回值的方法被调用,其定义为event EventHandler<PeripheralDiscoveredEventArgs> PeripheralDiscovered 当我使用IronPython运行此代码时,一切正常,因此我认为这是PythonNET的问题。我的代码如下:
from System import EventHandler, EventArgs

(...)

dc = EventHandler[PeripheralDiscoveredEventArgs](centralOnPeripheralDiscovered_callback)
central.PeripheralDiscovered += dc

iuc = EventHandler[EventArgs](systemInformationUpdated_callback)
central.SystemInformationUpdated += iuc
systemInformationUpdated_callback回调函数在调用centralOnPeripheralDiscovered_callback函数时不会被执行。
我还尝试了以下代码:
from System import EventArgs

(...)

EventHandler = getattr(System, 'EventHandler`1')
dc = EventHandler[PeripheralDiscoveredEventArgs](centralOnPeripheralDiscovered_callback)
central.PeripheralDiscovered += dc

EventHandler = getattr(System, 'EventHandler`1')
iuc = EventHandler[EventArgs](systemInformationUpdated_callback)
central.SystemInformationUpdated += iuc

我相信PythonNET 2.2已经修复了这个bug,所以它也不起作用了。

使用控制台,我得到以下结果:

dc
<0, Culture=neutral, PublicKeyToken=null]]>
iuc
<0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]>
对象的目标属性是
Target  <__System_EventHandler`1\[\[System_EventArgs\, mscorlib\, Version=4_0_0_0\, Culture=neutral\, PublicKeyToken=b77a5c561934e089\]\]Dispatcher>    __System_EventHandler`1\[\[System_EventArgs\, mscorlib\, Version=4_0_0_0\, Culture=neutral\, PublicKeyToken=b77a5c561934e089\]\]Dispatcher

我还查看了以下内容: 环境:
  • Python 3.6 64位,
  • PythonNET 2.3.0
  • .NET Framework 4.5.2
  • Windows 7 Enterprise 64位
非常感谢!

我正在尝试做类似的事情,并希望从您上面的代码中学到一些东西,但您只提供了片段。也许您可以更新一下这个问题,告诉我们您实际在控制台中输入了什么,或者在下面的答案中再详细解释一下? - not2qubit
对不起,我已经很久没有在这个上面工作了。我放弃了PythonNET并转向了IronPython。如果你想更多地了解C#委托和Python,我认为我在问题中列出的链接是一个很好的开端。 - Leonardo
1个回答

2

经过进一步测试,我意识到回调函数确实被调用了,很抱歉发出了虚假警报。我的回调函数如下:

def systemInformationUpdated_callback(sender, e):
    global central
    pdict = dict(central.SystemInformation)
    print "System Information:"
    for key, value in pdict.iteritems():
        print "    "+key+" = "+value

central.SystemInformation是一个IDictionary<string, string>。问题在于PythonNET无法直接从中创建字典,罪魁祸首是这一行:

pdict = dict(central.SystemInformation)

但这会悄悄地失败,没有抛出异常,也不会打印System Information:字符串。所以我认为回调函数从未被调用。

需要注意的是,这段代码在IronPython上运行良好。

谢谢!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接