Search code examples
c++pythonscriptingembeddingboost-python

Saving state of complex, scripted objects


In C++ I have the following two classes that I expose (using Boost) to Python:

struct Foo {
    // Empty
};

struct FooContainer {
    // I use boost::shared_ptr for compatibility with Boost.Python
    vector<boost::shared_ptr<Foo>> foos_;
};

In the Python side I might create a special type of Foo that actually does something instead of being just an empty class, and then add it to a FooContainer:

class Useful(Foo):
    def __init__(self, a, b):
        self.a = a
        self.b = b

x = Useful(3, 5);
# Add 'x' to a `FooContainer`

Back in the C++ side, the FooContainer now has some Foos, but it doesn't know or care that they are from Python. The application runs for a while and the data in the Foo objects changes...

Then I decide I want to save the state of my program so I can load it at a later time. But the problem is that FooContainer doesn't know much about its Foo objects, it doesn't even know that they come from Python and I wouldn't want to pollute my FooContainer with data that doesn't really belong in it (single-responsibility principle and all that).

Do you have any advice on how I should organize my application such that saving and loading data, as well as loading fresh data (ie. not from a state that I saved in the past) can be done in a clear way?


Solution

  • You can use boost::python/pickle, and save the data from python. I only have limited experience with the pickling suite, but it should work provided you override appropriate pickling methods in your classes derived in python (see my answer to this question).