How to make my SWIG extension module work with Pickle?

后端 未结 3 1577
孤独总比滥情好
孤独总比滥情好 2020-12-15 08:18

I have an extension module for Python that uses SWIG as a wrapper and I try to serialize it with Pickle and I fail =)

  1. If anyone has a source of SWIG extension
3条回答
  •  孤城傲影
    2020-12-15 09:03

    Seems like I found simlple solution that works for me:

    So let's say we have class C that was generated with SWIG, then we wrap it with

    class PickalableC(C, PickalableSWIG):
    
        def __init__(self, *args):
            self.args = args
            C.__init__(self)
    

    where PickalableSWIG is

    class PickalableSWIG:
    
        def __setstate__(self, state):
            self.__init__(*state['args'])
    
        def __getstate__(self):
            return {'args': self.args}
    

    Then

    pickle.loads(pickle.dumps(C()))
    

    fails, but

    pickle.loads(pickle.dumps(PickalableC()))
    

    succeeds =)

提交回复
热议问题