[Tutor] how obsolete is 2.2, and a pickle question
Peter Otten
__peter__ at web.de
Thu Sep 8 10:15:19 CEST 2011
c smith wrote:
> oh, and a question on 'pickle':
> can pickle deserialize things that were not serialized by python?
> can it convert data into a python data type regardless of it was
> originally a 'c array' or something else that python doesn't support?
As long as the file written by C is a valid pickle file and all classes used
are available to the Python interpreter you are fine:
$ cat pickledemo_struct.c
#include <stdio.h>
typedef struct NAMEDPAIR {
char name[10];
int x;
int y;
} namedpair;
main()
{
FILE *f = fopen("tmp_struct.pickle", "wb");
int i;
namedpair *p, data[] = {{"Cube", 10, 20}, {"Pyramid", 30, 40}};
fprintf(f, "(lp0\n");
for (i = 0, p = data; i != 2; i++, p++) {
fprintf(f, "(S'%s'\nI%d\nI%d\ntp%d\na", p->name, p->x, p->y, i+1);
}
fprintf(f, ".");
}
$ gcc pickledemo_struct.c
$ ./a.out
$ python -c 'import pickle; print pickle.load(open("tmp_struct.pickle"))'
[('Cube', 10, 20), ('Pyramid', 30, 40)]
But remember that in C the information whether you have a 32 bit integer or
four characters is in the code, not in the data; if you just dump that data
to a file Python can still read it, but has no way of knowing what it's
meant to be.
More information about the Tutor
mailing list