use*_*525 3 c++ arrays struct zeromq
我在发送从指向结构的指针构建的 zmq 消息时遇到问题,该结构包含其他结构。
服务器代码:
#include <zmq.hpp>
#include <string>
#include <iostream>
using namespace zmq;
using namespace std;
struct structB{
int a;
string c;
};
struct structC{
int z;
struct structB b;
};
int main()
{
context_t context(1);
socket_t *socket = new socket_t(context,ZMQ_REP);
socket->bind("tcp://*:5555");
message_t *request = new message_t();
socket->recv(request);
struct structB messageB;
messageB.a=0;
messageB.c="aa";
struct structC *messageC = new struct structC;
messageC->z = 4;
messageC->b = messageB;
char *buffer = (char*)(messageC);
message_t *reply = new message_t((void*)buffer,
+sizeof(struct structB)
+sizeof(struct structC)
,0);
socket->send(*reply);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
客户端代码:
#include <zmq.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace zmq;
struct structB{
int a;
string c;
};
struct structC{
int z;
struct structB b;
};
int main()
{
context_t context(1);
socket_t *socket = new socket_t(context,ZMQ_REQ);
socket->connect("tcp://*:5555");
const char* buffer = "abc";
message_t *request = new message_t((void*)buffer,sizeof(char*),0);
socket->send(*request);
message_t *reply = new message_t;
socket->recv(reply);
struct structC *messageC = new struct structC;
messageC = static_cast<struct structC*>(reply->data());
cout<<messageC->b.a<<endl;//no crash here
struct structB messageB = messageC->b;//Segmentation fault (core dumped)
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用 structB 中名为“c”的字符串时,该程序崩溃。如果我尝试打印它,或者像上面的例子那样分配整个 structB 都没有关系。
问题出在哪儿?我应该以不同的方式在服务器端创建 message_t *reply 吗?
您不能像容器一样通过网络发送字符串std::string。您可以使用灵活的数组成员或大数组或编写一个可序列化的小类(您必须自己编写代码来准备缓冲区)来发送数据。
当您这样做时struct structB messageB = messageC->b;,std::string嵌入在 messageC->b 中的成员的指针成员可能在复制构造函数中被取消引用,或者std::string这可能会导致分段错误。
大字符数组的示例是:
struct structB{
int a;
char c[MAX_LENGTH];
};
Run Code Online (Sandbox Code Playgroud)
之后
struct structB messageB;
messageB.a=0;
strcpy(messageB.c,"aa"); // #include<cstring> or use std::copy from <algorithm>
struct structC *messageC = new struct structC;
// I guess you want this(not sure) messageC->z = static_cast<int>( sizeof(int) + strlen(messageB) + 1 );
messageC->z = 4;
messageC->b = messageB;
Run Code Online (Sandbox Code Playgroud)
进而
const int length = sizeof(int) /* z */ + sizeof(int) /* a */ + strlen("aa") + 1;
zmq::message_t msg (length);
memcpy (msg.data (), &messageC, length);
socket->send(msg);
Run Code Online (Sandbox Code Playgroud)
这些是服务器端需要的一些更改,您也需要在客户端进行类似的更改。
作为旁注,您的代码非常混乱,在整理出一些事情(例如删除不必要的new和正确表示嵌套结构)之前,不要将其部署到更大的应用程序中。
| 归档时间: |
|
| 查看次数: |
3714 次 |
| 最近记录: |