這段代碼將struct序列化爲char數組,並且我可以通過套接字發送它並反序列化。C如何將結構數組序列化爲char數組?
如何修改此代碼使用結構的陣列
server_message[n].response = strdup("RESPONSE");
server_message[n].command = strdup("COMMAND");
server_message[n].data = strdup("DATA");
連載到字符數組 -
char reply[1024];
發送通過套接字和反序列化回來?
#include <string.h>
typedef struct __attribute__((__packed__)) arch_sm
{
char* response;
char* command;
char* data;
} request_struct_sm;
size_t serialize(const request_struct_sm* arch_sm, char* buf)
{
size_t bytes = 0;
memcpy(buf + bytes, arch_sm->response, strlen(arch_sm->response) + 1);
bytes += strlen(arch_sm->response) + 1;
memcpy(buf + bytes, arch_sm->command, strlen(arch_sm->command) + 1);
bytes += strlen(arch_sm->command) + 1;
memcpy(buf + bytes, arch_sm->data, strlen(arch_sm->data) + 1);
bytes += strlen(arch_sm->data) + 1;
return bytes;
}
void deserialize_server(const char* buf, request_struct_sm* arch_sm)
{
size_t offset = 0;
arch_sm->response = strdup(buf + offset);
offset += strlen(buf + offset) + 1;
arch_sm->command = strdup(buf + offset);
offset += strlen(buf + offset) + 1;
arch_sm->data = strdup(buf + offset);
}
int main(){
request_struct_sm server_message;
request_struct_sm client_message;
server_message.response = strdup("RESPONSE");
server_message.command = strdup("COMMAND");
server_message.data = strdup("DATA");
// server_message[0].response = strdup("RESPONSE"); //Need to be able use array of structure
// server_message[0].command = strdup("COMMAND");
// server_message[0].data = strdup("DATA");
char reply[1024] = {0};
size_t bufLen = serialize(&server_message, reply);
deserialize_server(reply, &client_message);
printf("client_message.response = %s\n"
"client_message.command = %s\n"
"client_message.data = %s\n",
client_message.response, client_message.command, client_message.data);
return 0;
}
感謝您的回覆!我也認爲,我已經使用這個解決方案http://stackoverflow.com/a/8941319/1564325,但改爲char a []我用回覆。我有一個問題,答覆只包含第一行「RESPONSE」。如何指定全長? –