[zeromq-dev] How to get buffer out of zmq_msg

john skaller skaller at users.sourceforge.net
Wed Feb 8 01:02:54 CET 2012

Is there a way to retrieve the buffer out of a zmq_msg after
a zmq_recvmsg? 

It does not appear so. This seems inefficient.

Let's assume you want a buffer for whatever reason.
If you pre-allocate it you own it, but you may not know how
big to make it. 

If you make it too small ZMQ simply loses part
of the message silently (this is a bug in the current implementation).

If you make it too big, you're wasting space. To be sure you'd
need to allocate rather a lot of memory.

If you initialise the message empty, zmq_recvmsg will allocate
exactly the right amount of space for you. This is ideal. 
But there's no way to get the buffer out of the msg, you have
to copy it. This is wastes a memcpy, and wastes storage temporarily.
You have to copy it because zmq_close will deallocate the buffer.

Of course .. you can *cheat* and simply not close the zmq_msg_t,
and in the current implementation I am guessing this would work.
You will later free the buffer with ::std::free, which also might or might 
not work.

It would be better if there were a way to properly take ownership
of the buffer e.g:

	// returns internal msg buffer, which can be
 	// deallocated with free()
	void *zmq_release(zmq_msg_t *);

I'm not sure how this would play with other msg functions.

BTW: for an analogous problem see C++ strings.
Same issue, worse problem: no way to capture either.
zmq_msg_t can capture user buffer.

john skaller
skaller at users.sourceforge.net

More information about the zeromq-dev mailing list