Serialize a variable length structure
-
Hello, I want to serialize structure like this: struct FRAME{ int Len;// size of Text following char Text[]; } ; the problem is that this is not a fixed length variable! how could I read the structures after being serialized? Thanks
-
Hello, I want to serialize structure like this: struct FRAME{ int Len;// size of Text following char Text[]; } ; the problem is that this is not a fixed length variable! how could I read the structures after being serialized? Thanks
Read 4 bytes first to get the length value. Now read the number of bytes identified by length.
«_Superman_» I love work. It gives me something to do between weekends.
-
Hello, I want to serialize structure like this: struct FRAME{ int Len;// size of Text following char Text[]; } ; the problem is that this is not a fixed length variable! how could I read the structures after being serialized? Thanks
The way it's usually done is something like this:
- Read
Len
from whatever you're reading from - Allocate a buffer of size
Len
+sizeof Len
bytes. - Copy
Len
into the firstsizeof Len
bytes of the buffer - Read
Len
bytes into the buffer after the copied value ofLen
- Cast the buffer pointer to FRAME* and return it
Let's presume you're reading from a C
FILE
:FRAME* ReadFRAME(FILE* file)
{
int Len;
fread((void*)&Len, sizeof(Len), 1, file);
char* space = (char*)malloc(Len + sizeof(Len));
FRAME* gotFrame = (FRAME*)space;
gotFrame->Len = Len;
fread((void*)gotFrame->Text, 1, Len, file);
return gotFrame;
}Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p
- Read