On Oct 30, 2013, at 6:36 PM, Chan, Jack wrote:

> Hi,
> 
> I'm having trouble initializing a TMemoryBuffer with contents. I serialized 
> an object (a ContactsList object) with TCompactProtocol and then wrote it out 
> as a file to disk. Now, I'm trying to read that file and create the same 
> object, but it appears that when I call the object's .read() function, it 
> says "No more data to read." I suspect that I did not correctly initialize 
> the TMemoryBuffer with anything. Here is what I'm doing:
> 
> // contacts_bin is a std::string that is read in from disk and is a binary 
> string encoded with TCompactProtocol)
> // contacts_bin_copy is a copy of contacts_bin except it's a char* instead of 
> a std::string.
> ContactsList object;
> shared_ptr<TMemoryBuffer> transportIn(new TMemoryBuffer((unsigned 
> char*)contacts_bin_copy, contacts_bin.size()));
> shared_ptr<TCompactProtocol> protocolIn(new TCompactProtocol(transportIn));
> object.read(protocolIn.get());
> 
> So, I am creating a new TMemoryBuffer by providing a string and the size of 
> that string to the constructor. I might not be doing it right, which is why 
> I'm getting problems. Might the buffer have nothing in it because I did not 
> change the memory policy to COPY? If that's the case, what's the correct code 
> that will do it?
> 
> Thanks,
> Jack
> 

Hi Jack,

Here's a function we use to do something very similar:

        template <class T>
        void    readThriftObjFromBuffer(const void* inBuffer, const size_t 
inBufferSize,
                                                                        T& 
outThriftStruct)
        {
                // Instance the memory buffer and simple binary protocol, then 
read the structure from it.
                boost::shared_ptr<TMemoryBuffer> memoryBuffer( new 
TMemoryBuffer(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(inBuffer)), 
inBufferSize, TMemoryBuffer::OBSERVE) );
                boost::shared_ptr<TProtocol> binaryProtocol( new 
TBinaryProtocol(memoryBuffer) );
                outThriftStruct.read(binaryProtocol.get());
        }

It seems to me that what you're doing should work. 

Have you verified that your write really worked and that contacts_bin_copy 
really points to a string that has nonzero size?

- Rush

Reply via email to