无法通过PyQt4传递参数给ActiveX COM对象
我正在尝试写一些Python代码来与Thorlabs APT的ActiveX控制进行交互。我是根据这个页面上的代码来写的,但我想用PyQt4的ActiveX容器,而不是wxPython的ActiveX容器。对于一些非常简单的ActiveX方法,这个方法是有效的,但是当我尝试调用一个需要参数的方法时,就出现了错误。
这段代码可以正常工作,并显示Thorlabs APT的关于框:
import sys
from ctypes import *
from PyQt4 import QtGui
from PyQt4 import QAxContainer
class APTSystem(QAxContainer.QAxWidget):
def __init__(self, parent):
self.parent = parent
super(APTSystem, self).__init__()
self.setControl('{B74DB4BA-8C1E-4570-906E-FF65698D632E}')
# calling this method works
self.AboutBox()
app = QtGui.QApplication(sys.argv)
a = APTSystem(app)
当我把self.AboutBox()
替换成一个需要参数的方法,比如:
num_units = c_int()
self.GetNumHWUnitsEx(21, byref(num_units))
我就会收到一个错误:TypeError: unable to convert argument 1 of APTSystem.GetNumHWUnitsEx from 'CArgObject' to 'int&'
我猜这个参数类型需要是ctypes类型。有没有什么ctypes的技巧可以解决这个问题呢?
1 个回答
1
结果发现我之前的语法写得完全不对。后来我通过使用 generateDocumentation()
这个函数,在这里提到的,以及一些参数帮助信息,来自这里的,才搞明白了。现在能正常工作的代码是:
import sys
from PyQt4 import QtGui
from PyQt4 import QAxContainer
from PyQt4.QtCore import QVariant
class APTSystem(QAxContainer.QAxWidget):
def __init__(self, parent):
super(APTSystem, self).__init__()
# connect to control
self.setControl('{B74DB4BA-8C1E-4570-906E-FF65698D632E}')
# required by device
self.dynamicCall('StartCtrl()')
# args must be list of QVariants
typ = QVariant(6)
num = QVariant(0)
args = [typ, num]
self.dynamicCall('GetNumHWUnits(int, int&)', args)
# only list items are updated, not the original ints!
if args[1].toInt()[1]:
print 'Num of HW units =', args[1].toInt()[0]
self.dynamicCall('StopCtrl()')
app = QtGui.QApplication(sys.argv)
a = APTSystem(app)
在 args
列表中的第二个项目包含了正确的值,但 num
这个变量在调用时从来没有被更新过。