ZeroMQ is offering a zero-copy technique, where networking copying data is avoided as much as possible. However it doesn't seem to work (as tested with ZeroMQ v4.1.5).
This is the server code:
void CustomCleanup(void *data, void *hint)
{
cout << "free1" << endl;
delete static_cast<std::string*>(hint);
}
void my_free (void *data, void *hint)
{
cout << "free2" << endl;
free (data);
}
int main()
{
//Allocate a string and zero copy it to client
std::string* messageString = new string("ABCDEFG");
cout << messageString->c_str() << endl;
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_PUSH);
socket.bind ("tcp://*:5555");
zmq_msg_t msg;
zmq_msg_init_data (&msg, messageString, messageString->length(), CustomCleanup, messageString);
zmq_send (socket, &msg, 7, 0);
cout << messageString->c_str() << endl;
//Malloc a data buffer and zero copy it to client
void *data = malloc (6);
assert (data);
memcpy (data, "ABCDEF", 6);
zmq_msg_t msg2;
int rc = zmq_msg_init_data (&msg2, data, 6, my_free, NULL); assert (rc == 0);
zmq_send (socket, &msg2, 6, 0);
}
And this is the client code:
int main()
{
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_PULL);
socket.connect ("tcp://127.0.0.1:5555");
zmq::message_t message;
socket.recv(&message);
}
After the call to each zmq_msg_init_data, the deallocators CustomCleanup and my_free should be called to free the allocated memory but in my case this does not happen. Why?
Note: In the server example i used both new/malloc and both string and void pointers to help pinpoint a potential fault, but it is not working in either case.