In the C language, I can save or load a variable to a binary file using fwrite/fread in the following way:
int main()
{
FILE *fl = fopen("data.bin", "w+");
FILE *fl2 = NULL;
struct foo_bar {
int x;
char y;
char *z;
};
struct foo_bar a, b;
a.x = 5;
a.y = '5';
a.z = NULL;
fwrite(&a, sizeof(struct foo_bar), 1, fl);
fclose(fl);
fl2 = fopen("data.bin", "r");
fread(&b, sizeof(struct foo_bar), 1, fl);
printf("%d %c %d", b.x, b.y, b.z);
return 0;
}
The key idea that is important to me here is that I don't have to parse a buffer of characters, and then use them to create some object of type
struct foo_bar
using a constructor, but rather I can just load it directly from the file.
My Question is: Is there a way to accomplish this functionality in Python?
Why would I want to do this?
I need to pass a list of socket objects from a python script to a sub-procedure, and the way my goal is typically accomplished is by first writing the sockets to a file, and then having the sub-procedure read them in from that file. The idea is that the clients which are connected through these sockets can then begin interacting with the sub-procedure, which takes over as the server.
But the best I have been able to do so far in Python is to save the file descriptors of the sockets to a file, load them from the sub-procedure, and then use them, along with the socket's constructor to make new sockets.
But attributes to the underlying _socket object are inaccessible to me, and hence I am unable to recover connectivity with my clients. I hope this makes sense, I have done my best to phrase this as carefully as I can. But if it's unclear please let me know and I'm happy to clarify anything further.