[英]C/C++ reading from a char buffer to populate a struct
我有一條通過UDP套接字發送的消息。 該消息的類型為RPCMessage
typedef struct
{
enum {Request, Reply} messageType;
unsigned int RPCId;
unsigned int procedure;
int arg1;
int arg2;
} RPCMessage;
當我准備發送消息時,我將消息構造如下:
RPCMessage toSend = {RPCMessage::Reply, htonl(rpcId), htonl(procedureId), htonl(int1), htonl(int2);
當我收到消息時,它會被接收到我稱為緩沖區的char []中。 有人建議,與其將整個緩沖區轉換為RPCMessage,不如讓我逐個讀取緩沖區中的每個參數,然后將第一個參數作為正確的枚舉類型並在ntohl上使用,會更好。彼此爭論。 做到這一點的最好方法就是:
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));
還是有另一種/更好的方法?
最好的方法是使用強大的序列化框架,如Boost序列化。
http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/index.html
這取決於您的消息的復雜程度。
我建議將其強制轉換為結構。 主要原因-性能。
您幾乎總是可以在結構的布局和緩沖區中的數據之間實現二進制兼容性。 有一些控制填充和對齊等的編譯指示。在C ++中,有專門的對齊規范。
我不想說just cast and problems will disappear
。 您仍然需要處理字節順序,字符repr可以不同,等等。
當您想對結構進行不同的表示或當數據結構很復雜(例如結構樹)時,應使用序列化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.