From the documentation at: https://brettviren.github.io/cppzmq-tour/index.html#intro, it seems that it is possible with CPPZMQ to send and receive a standard vector by using messages or buffers. However, I have not been able to use the vector from the subscriber, I get an error when trying to access it:
Segmentation error (core dumped)
when I run the following code:
Publisher:
#include <vector>
#include <iostream>
#include <zmq.hpp>
#include <thread>
using namespace std;
using namespace zmq;
int main()
{
vector<float> v(2, 0.0);
context_t ctx;
socket_t pub(ctx, ZMQ_PUB);
const std::string addr = "tcp://127.0.0.1:5678";
pub.bind(addr);
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
v = {0.1, 0.2};
message_t msg(v);
auto res = pub.send(msg, send_flags::none);
cout << "message sent" << endl;
}
}
Subscriber:
#include <vector>
#include <iostream>
#include <zmq.hpp>
using namespace std;
using namespace zmq;
int main()
{
context_t ctx;
socket_t sub(ctx, socket_type::sub);
const std::string addr = "tcp://127.0.0.1:5678";
sub.set(zmq::sockopt::subscribe, "");
sub.connect(addr);
message_t msg;
const vector<float>* iptr = msg.data<vector<float>>();
while (true)
{
if (sub.recv(msg, zmq::recv_flags::none))
{
cout << "msg received" << endl;
iptr = msg.data<vector<float>>();
cout << "iptr: " << iptr << endl;
cout << "element 0: " << (*iptr)[0] << "endl";
}
}
}
My question is:
How do I retrieve the vector in the publisher ? More generally, with a vector of constant length and type, I would need an efficient way to send and receive such vector, for example avoiding copy and avoiding reallocation and destruction at every message. What is the recommended way to do that ?