简体   繁体   English

从char缓冲区读取C / C ++以填充结构

[英]C/C++ reading from a char buffer to populate a struct

I have a message which is sent over a UDP socket. 我有一条通过UDP套接字发送的消息。 The message is of type RPCMessage 该消息的类型为RPCMessage

typedef struct
{
    enum {Request, Reply} messageType;
    unsigned int RPCId;
    unsigned int procedure;
    int arg1;
    int arg2;
} RPCMessage;

when I send am preparing to send a message, I construct the message as follows: 当我准备发送消息时,我将消息构造如下:

RPCMessage toSend = {RPCMessage::Reply, htonl(rpcId), htonl(procedureId), htonl(int1), htonl(int2);

When I receive the message, it is received into a char[] I call buffer. 当我收到消息时,它会被接收到我称为缓冲区的char []中。 It has been suggested that rather than just casting the entire buffer to an RPCMessage, it would be better to have something where I read each argument from the buffer one by one and then could have the first argument as the correct enum type and use ntohl on each other argument. 有人建议,与其将整个缓冲区转换为RPCMessage,不如让我逐个读取缓冲区中的每个参数,然后将第一个参数作为正确的枚举类型并在ntohl上使用,会更好。彼此争论。 Would the best way to do this just be something like: 做到这一点的最好方法就是:

RPCMessage::messageType type;
unsigned int id, procedure;
int int1, int2;
sscanf(buffer, %d%d%d%d%d, type, id, procedure, int1, int2);
RPCMessage received = {type, ntohl(id), ntohl(procedure), ntohl(int1), ntohl(int2));

or is there another/better way? 还是有另一种/更好的方法?

The best way would be to use a robust serialization framework like boost serialization. 最好的方法是使用强大的序列化框架,如Boost序列化。

http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/index.html http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/index.html

It depends how complex your messages can get. 这取决于您的消息的复杂程度。

I would recommend casting to structs. 我建议将其强制转换为结构。 Primary reason - performance. 主要原因-性能。

You can almost always achieve binary compatibility between the layout of your struct and the data in your buffer. 您几乎总是可以在结构的布局和缓冲区中的数据之间实现二进制兼容性。 There are pragmas that control padding and alignment, etc. In C++ there are special alignment specification for that. 有一些控制填充和对齐等的编译指示。在C ++中,有专门的对齐规范。

I do not want to say just cast and problems will disappear . 我不想说just cast and problems will disappear You still need to handle byte order, character repr can be different, etc. 您仍然需要处理字节顺序,字符repr可以不同,等等。

Serialization should be used when you want to have different repesentaion of your structs or when your data structure is complex, like a tree of structures. 当您想对结构进行不同的表示或当数据结构很复杂(例如结构树)时,应使用序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM