Boost Python:在类定义之外无法访问的扩展类对象

时间:2017-05-29 07:15:41

标签: python c++ python-3.x boost-python

我使用boost-python在python中扩展C ++回调类并从服务器接收数据。

我的C ++回调类有一个名为handleMsg的虚方法,我在python中覆盖了它。在覆盖中,我附加了传入的消息''列表。

这是我的C ++回调包装器

void export_Callback()
{
    class_< Callback>("Callback")
        .def(init<Callback>())
        .def("handleMsg", &Callback::handleMsg)
    ;
}

这是python子类

class SampleCallback(Callback):

    #numOfMsgs = 0
    #msgList = []
    def __init__(self):
        print('Initialising Callback...')        
        self.msgList = []
        self.numOfMsgs = 0
        Callback.__init__(self)

    def handleMsg(self, msg):        
        print('msg received')
        self.msgList.append(msg)
        print('Repr of list in class:')
        print(object.__repr__(self.msgList))
        self.numOfMsgs += 1
        self.printNumMsgs() #This gives updated value
        self.printList()      

    def getMsgList(self):
        return self.msgList

    def printList(self):
        print(self.msgList)

    def getNumOfMsgs(self):
        return self.numOfMsgs

    def printNumMsgs(self):
        print('Number of Messages in callback: '+str(len(self.msgList)))

以下是我启动应用程序的方式

    cb = SampleCallback();
    startServer()
    time.sleep(10)    
    startCppClient(cb) #cpp client sends messages to this object

    time.sleep(10)

    print('cb list size: '+str(len(cb.msgList)))
    print('Repr of list outside class:')
    print(object.__repr__(cb.msgList))
    print('cb num Of Msgs: '+str(cb.getNumOfMsgs()))
    print('Accessing print methods:')
    cb.printList() #This gives empty list
    cb.printNumMsgs()

以下是控制台日志:

Initialising Callback...
Starting Server 
Starting Client


msg received
Repr of list in class:
<list object at 0x7fd99e6b4dc8>
Number of Messages in callback: 1
[<component.msg object at 0x7fd99cf6fe08>]


msg received
Repr of list in class:
<list object at 0x7fd99e6b4dc8>
Number of Messages in callback: 2
[<component.msg object at 0x7fd99cf6fe08>, <component.msg object at 0x7fd99cf67868>]



cb list size: 0
Repr of list outside class:
<list object at 0x7fd99e6b4dc8>
cb num Of Msgs: 0
Accessing print methods:
[]
Number of Messages in callback: 0

正如您所看到的,对象。 repr ()方法在类定义和对象实例中打印相同的值,因此我得出结论,正在更新相同的列表。

但是,当从基类调用handleMsg方法时,列表似乎已填充,但cb对象的列表成员为空。

我在这里做错了什么?

任何指导都非常感谢。感谢

0 个答案:

没有答案