andreax79/python-cstruct

Make MemCStruct Pickle Friendly

Closed this issue · 1 comments

I tried to create a PR for this, but it looks like I don't have the ability to push a branch.

The changes to make this work are minimal so I'll document them here.

Adding the following methods to MemCStruct will allow it to become pickle friendly:

    def __getstate__(self):
        return self.pack()

    def __setstate__(self, data):
        return self.unpack(data)

And here is a test case to verify this:

import pickle

def test_pickle():
    # pickle an object
    original_pos = Position(head=254, sector=63, cyl=134)
    pickled_bytes = pickle.dumps(original_pos)

    # reconstitute a pickled object
    reconstituted_pos = pickle.loads(pickled_bytes)

    assert reconstituted_pos.head == original_pos.head
    assert reconstituted_pos.sector == original_pos.sector
    assert reconstituted_pos.cyl == original_pos.cyl

Great! Added to new version 3.1