[C++-sig] Read and write byte streams python<-->c++

Simon W simwarg at gmail.com
Wed Sep 29 14:08:13 CEST 2010


Hey,

I'm trying to serialise some data. I have a c++ class:
        class ostream
        {
            std::ostream& stream;
        public:
            ostream(std::ostream& s) : stream(s) {}

            void write(const char* bytes, Uint32 count)
            {
                stream.write(bytes, count);
            }
        };
As you can see, it only wraps std::ostream.

I call the python function like this:
ostream stream(file);
GameObject* obj = new GameObject(...);
                if(boost::python::override f = get_override("serialise"))
                    return f(boost::python::object(boost::python::ptr(obj)),
boost::python::object(boost::python::ptr(&stream)));

Then in the python script:
    def serialise(self, gameobj, file):
        if(gameobj in self.components):
            b = pickle.dumps(self.components[gameobj])
            # this is some testing code and dont really make sense because I
don't know what to do...
            file.write(str(len(str(b))), 10) # try to serialise an int that
tells the size of the byte-object
            print(len(str(b)))
            file.write(str(b), len(str(b))) # write the byte object
        return len(str(b)) + 10 # return amount of bytes we wrote

First i "pickle" a python object. I convert that byte-object to a string
since my write() function in c++ takes a const char*. But i'd like to pass
the byte-object directly since const char* is basically a byte, right?

Also, the other problem, when im about to read the serialised data I need to
know the size of the previously serialised data to unpickle it. I thoght
that I could to the c++ way and add a integer before the byte stream that
reveal how big it is. But How can i serialise an int from python that takes
up constant "byte-size" for an integer between lets say 0-10000!?

Any help on this one? Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20100929/4846d673/attachment.html>


More information about the Cplusplus-sig mailing list