将函数作为参数传递给COM对象函数

时间:2011-11-25 16:03:27

标签: python com upnp

我正在使用UPnP对象方法IUPnPDeviceFinder :: [CreateAsyncFind][1],第三个参数是回调函数。

我试图创建自己的COM对象,但该方法不会回调我的函数。这是我的代码:

class Callback():
    _public_methods_ = ['DeviceAdded','DeviceRemoved', 'SearchComplete']
    _reg_progid_ = "UPnP.PythonCallback"
    _reg_clsid_ = pythoncom.CreateGuid()

    def DeviceAdded  (device, UDN, calltype):
        print (device, ": ", calltype, " UDN: ", UDN)
        return
win32com.server.register.UseCommandLine(Callback)
callserver = Dispatch("UPnP.PythonCallback")
deviceType = "urn:schemas-upnp-org:device:MediaServer:1"
devices = finder.CreateAsyncFind(deviceType,0, callserver)
finder.StartAsyncFind(devices)

实际上,我只需要这样的东西:

def DeviceAdded  (device, UDN, calltype):
    print (device, ": ", calltype, " UDN: ", UDN)
    return
deviceType = "urn:schemas-upnp-org:device:MediaServer:1"
devices = finder.CreateAsyncFind(deviceType,0, DeviceAdded)
finder.StartAsyncFind(devices)

微软在VBScript上做了一个例子。这正是我想在Python上做的事情(http://msdn.microsoft.com/en-us/library/windows/desktop/aa381078(v=VS.85).aspx) 如何将函数作为参数传递给COM对象?

1 个答案:

答案 0 :(得分:1)

一个问题(可能不是唯一的问题)DeviceAdded是一个类的方法,因此它需要一个self参数:

def DeviceAdded(self, device, UDN, calltype):

我认为你的第一个例子是正确的,至少与你提供的链接中的VBScript(和C ++链接)相比。

此外,每次注册回调时都不应创建新的GUID。请致电pythoncom.CreateGuid一次,然后将结果粘贴到代码中:

# Use "print pythoncom.CreateGuid()" to make a new one.
_reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}"
相关问题