开发者

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开发者_JAVA技巧, 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?


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).


You already have python code that creates the Foos, lets call it populateFoos and somehow you have your program call it.

Now the next thing you need is a storeFoos and loadFoos function that does the saving and loading. If you want to keep it generic define them as storeFunc and loadFunc (or callback, depending on the context).

Depending on your program structure you might also need to keep in python a list of all foos created (or associated to a container).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜