thrift-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Chan, Jack" <>
Subject RE: initializing TMemoryBuffer in C++
Date Fri, 01 Nov 2013 18:28:25 GMT
Hi Rush,

Good to know that you're using the same way to deserialize something. Thanks for letting me
know! I printed out the string, and it wasn't empty. It turned out that it did not like the
.size() that I was giving it. I ended up giving it the length, and things worked. 


-----Original Message-----
From: Rush Manbert [] 
Sent: Thursday, October 31, 2013 9:21 AM
Subject: Re: initializing TMemoryBuffer in C++

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

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

View raw message