ネットワーク転送用に C で構造体を定義したいと考えています。たとえば、可変長の動物名を含む Animal 構造体を転送したいと考えています。
私の知る限り、1つの方法はusing a predefined length of char array
、またはusing a buffer
構造体であり、バッファを解析できます(たとえば、最初の4バイトは動物の名前の長さで、その後に動物の名前、および他のフィールドの長さと他のフィールドの値が続きます)、利点後者の方法の特徴は、次のコードが示すように、変数名の長さを許可することです。
struct Animal
{
char name[128];
int age;
}
また:
struct Animal
{
int bufferLen;
char* pBuffer;
}
私の質問は: 私のアプローチは正しいですか? つまり、構造体を転送する標準的な方法があり、より良い方法はありますか?
私の2番目の質問は、パディングに注意を払う必要がありますか、つまり使用する必要があります#pragma pack(push/pop, n)
か?
前もって感謝します!