我正在为同一平台编写 C++ ZeroMQ 客户端和服务器程序。我需要在服务器上使用参数触发一些函数。参数是复杂的结构。我刚开始尝试这个。我正在尝试填充一个结构并将其填充到 char* 缓冲区,以查看字节是否按照结构按顺序填充。
但是当我尝试打印缓冲区时,它打印出垃圾。请指教什么可能是错的。这是做到这一点的优雅方式吗?我不能使用 gRPC 或 Protobuffs,因为消息包含复杂的结构。
struct employee {
uint8_t byt;
int arr[10] = {0};
int number;
uint32_t acct;
};
int main ()
{
// Prepare our context and socket
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_PAIR);
struct employee *e = new employee;
e->byt = 0xff;
e->arr[0] = 15;
e->number = 25555;
e->acct = 45;
std::cout << "Connecting to hello world server…" << std::endl;
socket.connect ("tcp://localhost:5555");
char *temp = (char*)malloc(sizeof(employee));
memcpy(temp,e,sizeof(employee));
zmq::message_t request(sizeof(employee));
char *temp1 = temp;
for (int i = 0;i<sizeof(employee);i++) {
std::cout<<temp1[i]<<std::endl;
}
memcpy ((void *)request.data(),(void*)temp, sizeof(employee));
socket.send (request);
// Get the reply.
zmq::message_t reply;
socket.recv (&reply);
return 0;
}
最佳答案
我想在这里分享两点。
- 缓冲区 (temp) 包含您的数据结构的二进制表示。如果你想检查内容是否有意义,你可以将指针类型转换回它原来的指针。即:
struct employee * employeePtr = static_cast< struct employee *>(temp);
cout << employeePtr ->number;
...
当您尝试对对象进行反序列化时,您的反序列化方式是可行的 serialize 占用连续内存。如果不是这种情况,您将不得不以其他方式处理它们(例如使用流)。这种情况的例子包括:
当您有指向某些已分配内存的指针、shared_ptr 等时
容器类
关于c++ - 在客户端和服务器之间序列化复杂的 C++ 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54053322/