序列化一个结构体并通过socket用C ++发送它 [英] Serialize a struct and send it via socket with C++
问题描述
我会通过C ++套接字发送一个结构体。这是一个示例结构:
i would send a struct via C++ sockets. This is an example struct:
struct PIPPO
{
int x;
int y;
};
用于:
PIPPO test2;
test2.x = 10;
test2.y = 20;
我有上面的代码序列化并通过socket发送。问题是,如果我尝试获取测试变量的HEX值只看到0A和在接收数据的其他计算机上,我无法将二进制数据转换回结构。有人可以帮我吗?
and I have the code above to serialize and send it via socket. The problem is that if I try to get the HEX value of the test variable i only see 0A and infact on the other computer that receives the data I cannot convert back the binary data into a struct. Can someone help me?
template <class T> void SerializeData(char *outputArray, T inputData)
{
memcpy(outputArray, &inputData, sizeof(inputData));
}
char *StrToHexStr(char *str)
{
char *newstr = new char[(strlen(str)*2)+1];
char *cpold = str;
char *cpnew = newstr;
while('\0' != *cpold) {
sprintf(cpnew, "%02X", (char)(*cpold++));
cpnew+=2;
}
*(cpnew) = '\0';
return(newstr);
}
char *test = new char[sizeof(PIPPO)];
memcpy((void *)&test, (void *)&test2, sizeof(test2));
send(this->m_socket, test, strlen(test), 0);
推荐答案
问题,特别是当你有一个异构网络或应用程序。请查看可能最适合此操作的 protobuf 。
Sending a raw binary representation over the wire can cause you problem, specially when you have an heterogeneous network or applications. Have a look to protobuf which might be best suited for this.
这篇关于序列化一个结构体并通过socket用C ++发送它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!